paramiko是Python语言编写的遵循SSH2协议,支持加密和认证方式,连接远程服务器执行命令或者上传下载文件。
一、安装paramiko
1
|
pip3 install paramiko
|
二、使用用户名密码方式远程执行命令
1
2
3
4
5
6
7
8
|
import
paramiko
ssh
=
paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 自动接受远程服务器host key
ssh.connect(
'127.0.0.1'
,
22
,
'username'
,
'password'
)
# 远程主机IP、端口、用户名、密码
stdin, stdout, stderr
=
ssh.exec_command(
'df -h'
)
# 远程服务器要执行的命令
for
line
in
stdout:
print
(line)
ssh.close()
# 关闭ssh连接
|
三、使用用户名密码方式上传或下载文件
1
2
3
4
5
6
|
import
paramiko
t
=
paramiko.Transport(
'127.0.0.1'
,
22
)
t.connect(username
=
'username'
, password
=
'password'
)
sftp
=
paramiko.SFTPClient.from_transport(t)
sftp.put(
'local_file'
,
'remote_folder'
)
t.close()
|
1
2
3
4
5
6
|
import
paramiko
t
=
paramiko.Transport(
'127.0.0.1'
,
22
)
t.connect(username
=
'username'
, password
=
'password'
)
sftp
=
paramiko.SFTPClient.from_transport(t)
sftp.get(
'remote_file'
,
'local_folder'
)
t.close()
|
四、使用ssh key方式远程执行命令(前提远程主机已经接受了你的公钥)
1
2
3
4
5
6
7
8
9
10
11
|
import
paramiko
private_key_path
=
'/home/xxx/.ssh/id_rsa'
key
=
paramiko.RSAKey.from_private_key_file(private_key_path)
ssh
=
paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(
'127.0.0.1'
,
22
, username
=
'username'
, pkey
=
key)
stdin, stdout, stderr
=
ssh.exec_command(
'df'
)
print
(stdout.read())
ssh.close()
|
五、使用scp方式远程执行命令
1
2
3
4
5
6
7
8
|
import
paramiko
scp
=
paramiko.Transport((
'127.0.0.1'
,
22
))
scp.connect(username
=
'username'
, password
=
'password'
)
channel
=
scp.open_session()
channel.exec_command(
'touch hello/test.txt'
)
channel.close()
scp.close()
|
daibaiyang119