#!/usr/bin/python import pexpect import pxssh import getpass import sys hostname = raw_input('Enter the IP: ') username = raw_input('username: ') port = raw_input('port: ') password = getpass.getpass('password: ') root_pass =getpass.getpass('root_pass: ') s=pxssh.pxssh() s.login(hostname,username,password,original_prompt='[$#>]',port=port) #如果提示超时就在/usr/lib/python2.7/site-packages/pxssh.py的self.read_nonblocking(size=10000,timeout=1) #的上面添加 self.sendline() # time.sleep(0.5) #两行 s.sendline('su') #发送命令 x=s.expect(['Password']) #匹配命令生成的结果 if x==0: s.sendline(root_pass) y=s.expect(['root']) if y==0: print "su root success" s.sendline('cd /opt/linux_newcheck/linux_newcheck_20120413') z=s.expect(['linux_newcheck_20120413']) if z==0: print "Change directory success" s.sendline('./linux_chk.sh 192.168.0.2') while True: index = s.expect(["ALL",pexpect.TIMEOUT]) if index == 0: print "scanner ok" print s.before #打印命令输出的内容 break elif index == 1: print "scanner false" sys.exit(1) # return False elif index == 2: pass #continue to wait s.logout() #s.prompt() 这个方法是现实命令是否执行成功,如果是就返回ture,否则返回false