最近在看《Python自动化运维技术与最佳实战》这本书,学到了一个运维中用到的模块:pexpect
下面是其定义:
Pexpect 是一个用来启动子程序并对其进行自动控制的 Python 模块,它可以用来和像 ssh、ftp、passwd、telnet 等命令行程序进行自动交互。
从书中我摘取了相关实例并配有注释,用来记录pexpect常用方法:
下面这个实例功能是:以ssh远程登录,登录成功后执行命令‘ls -lh’
1 import pexpect 2 import sys 3 4 #通过spawn类启动和控制子应用程序 5 child = pexpect.spawn('ssh root@192.168.1.22') 6 7 #将pexpect的输入输出信息写到mylog.txt文件中 8 fout = file('mylog.txt','w') 9 child.logfile = fout 10 11 #将pexpect的输入输出信息输出到标准输出 12 #child.logfile = sys.stdout 13 14 #expect方法用来判断子程序产生的输出,判断是否匹配相应字符串 15 child.expect('password:') 16 #字符串匹配则使用sendline进行回应-----send:发送命令,不回车、sendline:发送命令,回车、sendcontrol:发送控制符,如:sendctrol('c')等价于‘ctrl+c'、sendeof:发送eof 17 child.sendline('123456') 18 child.expect('#') 19 child.sendline('ls -lh') 20 child.expect('#')