Python模块之 pexpect
Pexpect使Python成为控制其他应用程序的更好工具。可以理解为Linux下的expect的Python封装,通过pexpect我们可以实现对ssh,ftp,passwd,telnet等命令行进行自动交互,而无需人工干涉来达到自动化的目的。
简单示例:
#!/usr/bin/env python #coding:utf-8 import pexpect import sys IpAddress="192.168.56.103" LoginName="root" LoginPassword="123456" #通过spawn类启动和控制子应用程序 child=pexpect.spawn('ssh %s@%s' %(LoginName,IpAddress)) #expect方法用来判断子程序产生的输出,判断是否匹配相应字符串. child.expect('password:') child.sendline(LoginPassword) child.expect('#') #字符串匹配则使用sendline进行回应;send:发送命令,不回车、sendline:发送命令,回车 #sendcontrol:发送控制符,如:sendctrol('c')等价于‘ctrl+c'、sendeof:发送eof child.sendline('df -h') child.sendline("exit") child.interact() child.close()
参考文档:
https://www.cnblogs.com/lisenlin/p/9058557.html

浙公网安备 33010602011771号