使用pexpect提供的SSH模块登陆linux,并执行命令

pexpect安装:
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)

可以解决问题。

你可能感兴趣的:(ssh,pexpect,模拟登陆)