pexpect实现的ssh连接(pexpect可从sourceforge下载)
- def ssh_cmd(ip, passwd, cmd, newpwd):
- ret = –1
- ssh = pexpect.spawn(\’ssh -q -p36000 root@%s “%s”\’ % (ip, cmd))
- try:
- i = ssh.expect([\’password: \’, \’continue connecting (yes/no)?\’], timeout=5)
- if i == 0 :
- ssh.sendline(passwd)
- elif i == 1:
- ssh.sendline(\’yes\n\’)
- ssh.expect(\’password: \’)
- ssh.sendline(passwd)
- ssh.expect(\’New Password:\’)
- ssh.sendline(newpwd)
- ssh.expect(\’Reenter New Password:\’)
- ssh.sendline(newpwd)
- r = ssh.read()
- ret = 0
- except pexpect.EOF:
- print “EOF“
- ssh.close()
- ret = –1
- except pexpect.TIMEOUT:
- print “TIMEOUT“
- ssh.close()
- ret = –2
- return ret
- 参考:http://www.ibm.com/developerworks/cn/linux/l-cn-pexpect1/
版权声明:本文为cursorkey原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。