my11502207 发表于 2018-8-7 12:17:43

python 使用pexpect实现自动交互示例

from pexpect import pxssh  
import getpass
  

  
try:
  
    s = pxssh.pxssh()   #创建pxssh对象
  

  
    hostname = raw_input('hostname:')
  
    username = raw_input('username:')
  
    password = getpass.getpass('password:')   #接收密码输入
  

  
    s.login(server=hostname,username=username,password=password)#建立ssh连接
  

  
    s.sendline('uptime')#运行uptime命令
  
    s.prompt()   #匹配系统提示符
  
    print s.before#打印出现系统提示符前的命令输出
  

  
    s.sendline('ls -lh')#运行命令
  
    s.prompt()   #匹配系统提示符
  
    print s.before#打印出现系统提示符前的命令输出
  

  
    s.sendline('df -h')#运行命令
  
    s.prompt()   #匹配系统提示符
  
    print s.before#打印出现系统提示符前的命令输出
  

  
    s.logout()#断开ssh连接
  

  
except pxssh.ExceptionPxssh as e:
  
    print 'pxssh failed on login'
  
    print str(e)
页: [1]
查看完整版本: python 使用pexpect实现自动交互示例