测试环境: Ubuntu12.04
python-pexpect安装: apt-get install python-pexpect
测试脚本:
#!/usr/bin/env python import pxssh import getpass try: s = pxssh.pxssh() hostname = raw_input('hostname: ') username = raw_input('username: ') password = getpass.getpass('please input password: ') s.login(hostname, username, password) s.sendline('uptime') s.prompt() print s.before s.sendline('ls -l') s.prompt() print s.before s.sendline('df') s.prompt() print s.before s.logout() except pxssh.ExceptionPxssh, e: print "pxssh failed on login." print str(e)
执行时会报错:
Traceback (most recent call last):
File "pxsshsimple1.py", line 9, in <module>
s.login (hostname, username, password)
File "/usr/lib/python2.7/dist-packages/pxssh.py", line 243, in login
if not self.synch_original_prompt():
File "/usr/lib/python2.7/dist-packages/pxssh.py", line 134, in synch_original_prompt
self.read_nonblocking(size=10000,timeout=1) # GAS: Clear out the cache before getting the prompt
File "/usr/lib/python2.7/dist-packages/pexpect.py", line 824, in read_nonblocking
raise TIMEOUT ('Timeout exceeded in read_nonblocking().')
pexpect.TIMEOUT: Timeout exceeded in read_nonblocking().
修改/usr/lib/python2.7/dist-packages/pxssh.py文件,在line134行前增加:
self.sendline() time.sleep(0.5)