tar -zxvf pexpect-2.3.tar.gz
解壓後使用root進行安裝:
#python setup.py install
在linux下進行登錄腳本:
#!/usr/bin/env python
import pxssh
import getpass
try:
s = pxssh.pxssh()
hostname = raw_input('hostname: ')
username = raw_input('username: ')
password = getpass.getpass('password: ')
s.login (hostname, username, password)
s.sendline ('uptime') # run a command,
s.prompt() # match the prompt
print s.before # print everything before the propt.
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 "./sshlinux.sh", line 10, in <module>
s.login (hostname, username, password)
File "/usr/local/python-2.7/lib/python2.7/site-packages/pxssh.py", line 243, in login
if not self.synch_original_prompt():
File "/usr/local/python-2.7/lib/python2.7/site-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/local/python-2.7/lib/python2.7/site-packages/pexpect.py", line 824, in read_nonblocking
raise TIMEOUT ('Timeout exceeded in read_nonblocking().')
pexpect.TIMEOUT: Timeout exceeded in read_nonblocking().
這個問題可以調整錯誤信息中的路徑進行修改/usr/local/python-2.7/lib/python2.7/site-packages/pxssh.py文件,在pxssh.py文件中:
在def synch_original_prompt (self):方法下第一個self.read_nonblocking(size=10000,timeout=1) 前面增加兩行代碼
self.sendline()
time.sleep(0.5)
可以解決問題。