分类: Python/Ruby
2011-05-16 15:27:12
模块paramiko试用
#2011-05-16 磁针石
#承接软件自动化实施与培训等gtalk: ouyangchongwu#gmail.com qq 37391319 博客:oychw.cublog.cn
#版权所有,转载刊登请来函联系
#python qq group: 深圳自动化测试python群:113938272
#武冈深圳qq群:66250781
调试环境:
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]
paramiko-1.7.6
存在以后在windows上面使用ssh登陆linux自动化的可能,故看了一下paramiko,下面的实例程序通过ssh登陆到服务器,执行uptime命令。
Paramiko果然无法和ssh的王牌模块pexpect相比,可惜pexpect不支持windows,今后会继续优先选择linux作为部署环境。
#!/usr/bin/env python
#2011-05-16 磁针石
#承接软件自动化实施与培训等gtalk: ouyangchongwu#gmail.com qq 37391319 博客:oychw.cublog.cn
#版权所有,转载刊登请来函联系
#python qq group: 深圳自动化测试python群:113938272
#武冈深圳qq群:66250781
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#ssh.connect("192.168.190.131",22,"root", "birsk0")
ssh.connect("192.168.191.253",22,"andrew", "123456")
stdin, stdout, stderr = ssh.exec_command("uptime")
print stdout.readlines()
ssh.close()
执行结果:
[' 15:22:02 up 49 days, 23:09, 33 users, load average: 6.72, 7.31, 7.75\n']
chinaunix网友2011-05-19 15:54:23
你可以试试pexpect嘛,这里有个示例函数: def ssh_command(ip, passwd,command): """ 登录到一台机器执行执行的命令,取回返回结果 """ ssh_newkey = 'Are you sure you want to continue connecting' # 为 ssh 命令生成一个 spawn 类的子程序对象. child = pexpect.spawn('ssh -q -p36000 soso_plt@'+ip + " " + command) i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password:']) # 如果登录超时,打印出错信息,并退出. if i == 0: # Timeout print 'ERROR!' print 'SSH could not login. Here is what SSH said:' print child.b