
pexpect
发布日期:2021-05-07 18:06:24
浏览次数:17
分类:技术文章
本文共 2184 字,大约阅读时间需要 7 分钟。
pexpect是一个纯pyth实现的模块,pexpect可以某些交互式子进程进行交互从而代替手工操作。比如使用passwd命令需要人工输入密码,如果使用pexpect可以通过sendline自动化进行。
几个关键词掌握了就可以使用了。 spawn expect sendline before after# This connects to the openbsd ftp site and# downloads the recursive directory listing.import pexpectchild = pexpect.spawn('ftp ftp.openbsd.org')child.expect('Name .*: ')child.sendline('anonymous')child.expect('Password:')child.sendline('noah@example.com')child.expect('ftp> ')child.sendline('lcd /tmp')child.expect('ftp> ')child.sendline('cd pub/OpenBSD')child.expect('ftp> ')child.sendline('get README')child.expect('ftp> ')child.sendline('bye')
使用方法
pip install pexpect或者 python setup.py installimport pexpect
# 建立一个子进程 child = pexpect.spawn(‘ls’)# 去查找子进程返回的字符串
# pattern is a re string child.expect(pattern)child.before 这个值包含文本从头一直到匹配的位置
child.after 这个值就是匹配pattern的部分如果子进程结束了,你再去child.expect(pattern)会报EOF错误,模块提供了一种方法,child.expect(pexpect.EOF),不会报错,如果子进程结束了返回0
child2 = pexpect.spawn(‘passwd test’)
child2.expect(‘.*’) print child2.after mypasswd = ‘abcdefg’ child2.sendline(mypasswd) child2.expect(‘.*’) child2.sendline(mypasswd) print child.aftersendline的作用就好像是从终端中输入的,把字符串发送给子进程。
当有子进程有多种回复情形时,可以使用如下方法
i = child.expext([pattern1, pattern2] if i == 0: print “it’s mean pattern1 is searched” if i ==1: print “it’s mean pattern2 is searched”child.expect('password:')child.sendline(my_secret_password)# We expect any of these three patterns...i = child.expect (['Permission denied', 'Terminal type', '[#\$] '])if i==0: print('Permission denied on host. Can\'t login') child.kill(0)elif i==1: print('Login OK... need to send terminal type.') child.sendline('vt100') child.expect('[#\$] ')elif i==2: print('Login OK.') print('Shell command prompt', child.after)
当使用expect()没有匹配的期望的值,程序停住,过了timeout的时间会报超时错误
如果你使用了expect不管有没有匹配到,子进程都是已经把字符串给返回来了,没有进一步返回值时,再次使用expect没有意义了。
If nothing matches an expected pattern then expect() will eventually raise a TIMEOUT exception. The default time is 30 seconds, but you can change this by passing a timeout argument to expect():# Wait no more than 2 minutes (120 seconds) for password prompt.child.expect('password:', timeout=120)child.expect('abdccc', timeout=30)
发表评论
最新留言
留言是一种美德,欢迎回访!
[***.207.175.100]2025年03月27日 04时53分03秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
js 的 let var const 区别
2019-03-05
无线掌上B超USONIX-R6线阵B模图像初步
2019-03-05
无线掌上B超USONIX-R6凸阵B模图像初步
2019-03-05
react路由使用以及封装
2019-03-05
vue计算属性和监听器区别
2019-03-05
前端常用知识随手记
2019-03-05
react-redux使用hooks替代connect
2019-03-05
使用 FileUpload 实现文件上传
2019-03-05
11.2.6 时间值的小数秒
2019-03-05
11.2.7 日期和时间类型之间的转换
2019-03-05
附录 B 错误信息和常见问题
2019-03-05
第4章 MySQL 程序
2019-03-05
设置柱形图的柱的宽度
2019-03-05
c/c++ 学习
2019-03-05
redis 内存溢出_从数据存储的角度告诉你Redis为什么这么快!
2019-03-05
java gradle 目录_拆分Gradle中的所有输出目录
2019-03-05
http+flv+java,制作一个全功能的FLV播放器
2019-03-05
php寻找文本,寻找文本 · Leing中文PHP框架 · 看云
2019-03-05
实例分析Facebook激励视频广告接入
2019-03-05
实例:使用OKGO下载网络压缩包资源,然后解压缩放在本地使用
2019-03-05