pexpect官方网站
http://pexpect.sourceforge.net/
pexpect是一个可以模拟终端用户与系统的交互的Python库。
今天学习了一下,写了一个简单的试验程序在ubuntu上执行:
from pexpect import *
child = spawn ('bash')
child.expect('[#/$] ', timeout=5)
child.sendline('ls')
child.expect('[#/$] ', timeout=5)
print child.before
child.sendline('ls -l')
i = child.expect(['(?i)readme','(?i)etc', EOF, TIMEOUT])
if i==0:
print 'i==0 README'
child.sendline('ls /')
i = child.expect(['(?i)etc','(?i)readme',EOF, TIMEOUT])
if i==0:
print 'etc'
else:
print 'no etc.'
elif i==1:
print 'i==1'
print 'etc'
child.sendline('exit')
print 'end.'
首先执行一个bash,然后执行ls,看当前目录有没有readme文件(?i)代表不区分大小写,如果有,执行i==0分支,否则是o==1分
支,i==0分支中又执行了"ls /",看根目录有没有etc或者readme,并显示结果,最后退出bash。
运行通过。
bash的情况比较简单,再试验一个稍微复杂一点的:
def testSSH():
pwd = 'errpwd'
child = spawn ('ssh 192.168.1.1')
child.sendline(pwd)
i = 0
while i==0:
i = child.expect(['(?i)password', '[#/$] ' , EOF, TIMEOUT])
print child.before
print child.after
if i==1:
child.sendline('exit')
elif i==0:
pwd = 'rightpwd'
child.sendline(pwd)
这里模拟了一个ssh登录的过程,首先我们尝试用一个错误的密码登录,ssh不会报错,而是继续出现password提示符,再得到这个expect之
后,我们再尝试正确的密码,成功后退出ssh,并跳出while循环,程序结束。