下面我们讲下Pexpect的重要函数都有哪些。
首先Pexpect有两个主要执行命令的接口run()和spawn(),run()功能比较简单,如果只是执行简单的命令,并读取结果,可以使用run函数
pexpect.run('ls -al')
而spawn类功能强大,支持与远程计算机的交互。
一、spawn(command, args=,[]timeout=30,maxread=2000,searchwindowsize=None, logfile=None, cwd=None, env=None,ignore_sighup=True, echo=True)
其中命令和命令参数有以下两种方式,都是可以的。
1.
child = pexpect.spawn('/usr/bin/ftp')
child = pexpect.spawn('/usr/bin/ssh user@example.com')
child = pexpect.spawn('ls -latr /tmp')
2.
child = pexpect.spawn('/usr/bin/ftp', [])
child = pexpect.spawn('/usr/bin/ssh', ['user@example.com'])
child = pexpect.spawn('ls', ['-latr', '/tmp'])
而且spawn不支持重定向、管道、通配符(>, |, or *)等符号. 如果你需要使用这些符号,需要调用shell命令。
child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > logs.txt"')
child.expect(pexpect.EOF)
二、expect
(
pattern,
timeout=-1,
searchwindowsize=-1
)
expect()前面已经学过了,这里主要指出一点,以下两种形式是完全等价的。
1.
index=p.expect(['good','bad',pexpect.EOF,pexpect.TIMEOUT])
if index == 0:
do_something()
elif index ==1:
do_something_else()
elif index ==2:
do_some_other_thing()
elif index ==3:
do_something_completely_different()
2.
try:
index = p.expect(['good','bad'])
if index ==0:
do_something()
elif index ==1:
do_something_else()
except EOF:
do_some_other_thing()
except TIMEOUT:
do_something_completely_different()
三、send(), sendline(), sendcontrol()用来发送字符和字符串给远端子程序。
四、read(), readline()用来读取子程序返回的数据
五、interact() 把与子程序的交互控制交给用户,使用户可以直接控制子程序,使用ESC退出
控制子程序常用函数
isalive() 查看子程序是否活着
wait()阻塞等待子程序退出
close()关闭与子程序的连接
pid() 子程序的进程ID
讲完spawn类之后,我们扒一扒pexpect对ssh的扩展类pxssh。pxssh主要扩展了以下三个函数,login(), logout(), prompt().prompt()相当于expect()函数
import pxssh
import getpass
try:
s = pxssh.pxssh()
hostname = raw_input('hostname: ')
username = raw_input('username: ')
password = getpass.getpass('password: ')
s.login(hostname, username, password)
s.sendline('uptime') # run a command
s.prompt() # match the prompt
print(s.before) # print everything before the prompt.
s.sendline('ls -l')
s.prompt()
print(s.before)
s.sendline('df')
s.prompt()
print(s.before)
s.logout()
except pxssh.ExceptionPxssh as e:
print("pxssh failed on login.")
print(e)
Pexpect常用的应该就是这些了,而且这些功能应该已经能够支持完成大多数任务了。楼主也是刚刚开始使用,总体感觉pexpect算简单易懂了,但是还是有一些疑问没有解决,尤其是子程序执行时间比较长的时候,总感觉程序不在我的掌控之内,还得继续努力学习,同时也希望高手能不吝赐教。