23313 发表于 2016-5-11 09:51:32

python paramiko使用

paramiko 安装

1
2
yum install python-paramiko -y
yum install openssh-server openssh-clients -y




报错

1
2
3
4
5
6
7
8
Traceback (most recent call last):
File "ssh.py", line 10, in <module>
    ssh.connect(hostname=hostname,port=port,username=username,password=password)
File "/usr/lib/python2.6/site-packages/paramiko/client.py", line 306, in connect
    self._policy.missing_host_key(self, hostname, server_key)
File "/usr/lib/python2.6/site-packages/paramiko/client.py", line 83, in missing_host_key
    raise SSHException('Unknown server %s' % hostname)
paramiko.SSHException: Unknown server 192.168.2.11





解决方法一
1、创建 ~/.ssh/known_hosts
2、远程连接一次
eg

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python
import paramiko
hostname='192.168.2.11'
username='root'
password='oracle'
port=22

ssh=paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.connect(hostname=hostname,port=port,username=username,password=password)
stdin,stdout,stderr=ssh.exec_command('ls /')
print stdout.read()
ssh.close()





解决方法二
将ssh.load_system_host_keys()替换为set_missing_host_key_policy(paramiko.AutoAddPolicy())
eg

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/env python
import paramiko
hostname='10.13.106.36'
port=22
username='root'
password='centos'
if __name__=='__main__':
      paramiko.util.log_to_file('paramiko.log')
      s=paramiko.SSHClient()
      s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
      s.connect(hostname,port,username,password)
      stdin,stdout,stderr=s.exec_command('ifconfig')
      print stdout.read()
      s.close()






页: [1]
查看完整版本: python paramiko使用