Pexpect 学习
ucloud learning
Pexpect的作用
Pexpect can be used for automating interactive applications such as ssh, ftp, mencoder, passwd, etc. The Pexpect interface was designed to be easy to use.
说白了,Pexpect可以进行将输入和输出程序化,从而达到自动化运行交互式应用的目的。
原理:
常用API
import pexpect
response = pexpect.spawn(command)
child = pexpect.spawn(command)
child.expect([regular expression])
child.send(string)
child.sendline(string)
API | 参数 | 说明 | 返回值 |
---|---|---|---|
run | run(command) | 简单,执行command,返回输出,结束 | 返回命令的输出 |
spawn | spawn(command) | 交互性更强,启动一个管道,传递command的输入和输出 | 返回一个子程序 |
expect | spawn([regular expression]) | 等待子程序返回满足正则表达式列表中任意一项的字符串 | 返回正则表达式列表中匹配到的项的 索引 |
send | send(string) | 向子程序发送一个字符串,效果相当于在终端输入一个文本 | |
sendline | sendline(string) | 作用同send,但是会包括一个换行符,所以一般用这个,不用send |
常用属性
before和after
expect、send和 sendline 都是和 child 进行交互的 API. child 还有两个属性也很重要: before 和 after。before可以打印出expect匹配项之前child所有的打印,after可以打印出expect匹配到的项。
the before and after properties will be set to the text printed by child application
The before property will contain all text up to the expected string pattern. The after string will contain the text that was matched by the expected pattern
import pexpect
child = pexpect.spawn(command)
child.expect(regular expression)
print child.before # 打印出正则匹配到的字符串之前所有的字符串。
print child.after # 打印出正则匹配到的字符串
timeout
在expect中可以指定等待返回的超时时间,默认是30s。
比如我们设置等待child打印出’password:’的时间是120s:
child.expect('password:', timeout=120)
例子
登录到远程主机,执行ping命令,查看返回结果。
import pexpect
child=pexpect.spawn('ssh root@106.75.47.195 \'ping -c 1 10.13.46.101\'')
child.expect('*******')
child.sendline('ucloud.cn')
isPingSucceed=child.expect(['100% packet loss', '0% packet loss'])
print isPingSucceed
print child.before
print child.after
打印结果
Note:
- 匹配一行末尾: 不要使用$或者’\n’,使用”\r\n”
- Pexpect更多的API接口说明 http://pexpect.readthedocs.io/en/stable/api/pexpect.html