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 install

import 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.after

sendline的作用就好像是从终端中输入的,把字符串发送给子进程。

当有子进程有多种回复情形时,可以使用如下方法

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)
上一篇:python 标准库之os
下一篇:python pexpect

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2025年03月27日 04时53分03秒