Pexpect学习

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参数说明返回值
runrun(command)简单,执行command,返回输出,结束返回命令的输出
spawnspawn(command)交互性更强,启动一个管道,传递command的输入和输出返回一个子程序
expectspawn([regular expression])等待子程序返回满足正则表达式列表中任意一项的字符串返回正则表达式列表中匹配到的项的 索引
sendsend(string)向子程序发送一个字符串,效果相当于在终端输入一个文本
sendlinesendline(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

打印结果
Pexpect Test

Note:

  1. 匹配一行末尾: 不要使用$或者’\n’,使用”\r\n”
  2. Pexpect更多的API接口说明 http://pexpect.readthedocs.io/en/stable/api/pexpect.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值