SSHClient
用于连接远程服务器并执行基本命令
基于用户名密码连接:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import
paramiko
# 创建SSH对象
ssh
=
paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname
=
'c1.salt.com'
, port
=
22
, username
=
'wangsen'
, password
=
'123'
)
# 执行命令
stdin, stdout, stderr
=
ssh.exec_command(
'df'
)
# 获取命令结果
result
=
stdout.read()
# 关闭连接
ssh.close()
|
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
import paramiko transport = paramiko.Transport(('hostname', 22)) transport.connect(username='wupeiqi', password='123') ssh = paramiko.SSHClient() ssh._transport = transport stdin, stdout, stderr = ssh.exec_command('df') print stdout.read() transport.close()
基于公钥密钥连接:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import
paramiko
private_key
=
paramiko.RSAKey.from_private_key_file(
'/home/auto/.ssh/id_rsa'
)
# 创建SSH对象
ssh
=
paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname
=
'c1.salt.com'
, port
=
22
, username
=
'wangsen'
, key
=
private_key)
# 执行命令
stdin, stdout, stderr
=
ssh.exec_command(
'df'
)
# 获取命令结果
result
=
stdout.read()
# 关闭连接
ssh.close()
|
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
import paramiko private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa') transport = paramiko.Transport(('hostname', 22)) transport.connect(username='wupeiqi', pkey=private_key) ssh = paramiko.SSHClient() ssh._transport = transport stdin, stdout, stderr = ssh.exec_command('df') transport.close()