python的pexpect模块
Pexpect 是 Don Libes 的 Expect 语言的一个 Python 实现,是一个用来启动子程序,并使用正则表达式对程序输出做出特定响应,以此实现与其自动交互的 Python 模块。 Pexpect 的使用范围很广,可以用来实现与 ssh、ftp 、telnet 等程序的自动交互;可以用来自动复制软件安装包并在不同机器自动安装;还可以用来实现软件测试中与命令行交互的自动化。Pexpect仅能在Unix/Linux平台下使用。
1.1 run函数
run(command, timeout=-1, withexitstatus=False, events=None, extra_args=None, logfile=None, cwd=None, env=None)
若不指定withexitstatus参数,则返回command执行后的返回值,若指定withexitstatus为True,则返回一个包含退出状态的元组。
>>> res = pexpect.run('ls -l /var')
>>>(res,exitcode) = pexpect.run(‘ls –l /var’,withexitstatus=True)
>>> print(res.replace('\r\n','\n'))
总用量 52
drwxr-xr-x 2 root root 4096 9月 21 2014 agentx
drwxr-xr-x 2 root root 4096 2月 5 2015 backups
drwxr-xr-x 21 root root 4096 3月 28 2015 cache
drwxr-xr-x 71 root root 4096 3月 28 2015 lib
drwxrwsr-x 2 root staff 4096 2月 5 2015 local
lrwxrwxrwx 1 root root 9 3月 28 2015 lock -> /run/lock
drwxr-xr-x 21 root root 4096 7月 12 21:36 log
drwxrwsr-x 2 root mail 4096 2月 6 2015 mail
drwxr-xr-x 2 root root 4096 2月 6 2015 opt
lrwxrwxrwx 1 root root 4 3月 28 2015 run -> /run
drwxr-xr-x 6 root root 4096 3月 28 2015 spool
drwxrwxrwt 2 root root 4096 7月 21 20:33 tmp
drwxr-xr-x 2 root root 4096 6月 27 2013 unicornscan
drwxr-xr-x 2 root root 4096 7月 11 2015 workspace
drwxr-xr-x 2 root root 4096 3月 28 2015 www
>>>print(exitcode)
0
2. spawn类
__init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None)
This is the constructor. The command parameter may be a string that includes a command and any arguments to the command. For example::
child = pexpect.spawn ('/usr/bin/ftp')
child = pexpect.spawn ('/usr/bin/ssh user@example.com')
child = pexpect.spawn ('ls -latr /tmp')
You may also construct it with a list of arguments like so::
child = pexpect.spawn ('/usr/bin/ftp', [])
child = pexpect.spawn ('/usr/bin/ssh', ['user@example.com'])
child = pexpect.spawn ('ls', ['-latr', '/tmp'])
>>>child = pexpect.spawn('ls –l /var')
>>> child = pexpect.spawn('ls',['-l','/var'])
>>>res = child.readlines()
>>> for line in res:
... print(line.strip('\r\n'))
...
总用量 52
drwxr-xr-x 2 root root 4096 9月 21 2014 agentx
drwxr-xr-x 2 root root 4096 2月 5 2015 backups
drwxr-xr-x 21 root root 4096 3月 28 2015 cache
drwxr-xr-x 71 root root 4096 3月 28 2015 lib
drwxrwsr-x 2 root staff 4096 2月 5 2015 local
lrwxrwxrwx 1 root root 9 3月 28 2015 lock -> /run/lock
drwxr-xr-x 21 root root 4096 7月 12 21:36 log
drwxrwsr-x 2 root mail 4096 2月 6 2015 mail
drwxr-xr-x 2 root root 4096 2月 6 2015 opt
lrwxrwxrwx 1 root root 4 3月 28 2015 run -> /run
drwxr-xr-x 6 root root 4096 3月 28 2015 spool
drwxrwxrwt 2 root root 4096 7月 21 20:33 tmp
drwxr-xr-x 2 root root 4096 6月 27 2013 unicornscan
drwxr-xr-x 2 root root 4096 7月 11 2015 workspace
drwxr-xr-x 2 root root 4096 3月 28 2015 www
3. spawn实例child的方法
expect(self, pattern, timeout=-1, searchwindowsize=None)
在参数中: pattern 可以是正则表达式, pexpect.EOF , pexpect.TIMEOUT ,或者由这些元素组成的列表。需要注意的是,当 pattern 的类型是一个列表时,且子程序输出结果中不止一个被匹配成功,则匹配返回的结果是缓冲区中最先出现的那个元素,或者是列表中最左边的元素。使用 timeout 可以指定等待结果的超时时间 ,该时间以秒为单位。当超过预订时间时, expect 匹配到pexpect.TIMEOUT。
expect() 在执行中可能会抛出两种类型的异常分别是 EOF and TIMEOUF,其中 EOF 通常代表子程序的退出, TIMEOUT 代表在等待目标正则表达式中出现了超时。
try:
index = child.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()
expect 不断从读入缓冲区中匹配目标正则表达式,当匹配结束时 pexpect 的 before 成员中保存了缓冲区中匹配成功处之前的内容, pexpect 的 after 成员保存的是缓冲区中与目标正则表达式相匹配的内容。
>>> child = pexpect.spawn('ls -l /var')
>>> child.expect(pexpect.EOF)
0
>>> print child.before
总用量 52
drwxr-xr-x 2 root root 4096 9月 21 2014 agentx
drwxr-xr-x 2 root root 4096 2月 5 2015 backups
drwxr-xr-x 21 root root 4096 3月 28 2015 cache
drwxr-xr-x 71 root root 4096 3月 28 2015 lib
drwxrwsr-x 2 root staff 4096 2月 5 2015 local
lrwxrwxrwx 1 root root 9 3月 28 2015 lock -> /run/lock
drwxr-xr-x 21 root root 4096 7月 12 21:36 log
drwxrwsr-x 2 root mail 4096 2月 6 2015 mail
drwxr-xr-x 2 root root 4096 2月 6 2015 opt
lrwxrwxrwx 1 root root 4 3月 28 2015 run -> /run
drwxr-xr-x 6 root root 4096 3月 28 2015 spool
drwxrwxrwt 2 root root 4096 7月 21 20:33 tmp
drwxr-xr-x 2 root root 4096 6月 27 2013 unicornscan
drwxr-xr-x 2 root root 4096 7月 11 2015 workspace
drwxr-xr-x 2 root root 4096 3月 28 2015 www
>>> print child.after
<class 'pexpect.EOF'>
send(self, s)
sendline(self, s='')
sendcontrol(self, char)
这些方法用来向子程序发送命令,模拟输入命令的行为。 与 send() 不同的是 sendline() 会额外输入一个回车符 ,更加适合用来模拟对子程序进行输入命令的操作。 当需要模拟发送 “Ctrl+c” 的行为时,还可以使用 sendcontrol() 发送控制字符。
child.sendcontrol('c') #发送crtl + c
由于 send() 系列函数向子程序发送的命令会在终端显示,所以也会在子程序的输入缓冲区中出现,因此不建议使用 expect 匹配最近一次 sendline() 中包含的字符。否则可能会在造成不希望的匹配结果。
4. ftp交互实例
>>> import pexpect
>>> child = pexpect.spawn('ftp 192.168.1.102')
>>> child.expect('Name.*')
0 #只匹配一个正则‘Name.*’,因此返回0
>>> child.sendline('ftp_admin')
10
>>> child.expect('Password:')
0
>>> child.sendline('password')
9
>>> child.expect('ftp>')
0
>>> child.sendline('get NmapScanner.py')
19
5. pxssh类的使用
Pxssh 做为 pexpect 的派生类可以用来建立一个 ssh 连接,它相比其基类增加了如下方法:
login() 建立到目标机器的ssh连接 ;
losuckgout() 释放该连接 ;
prompt() 等待提示符,通常用于等待命令执行结束。
>>> import pxssh
>>> s = pxssh.pxssh()
>>> s.login('xx.xx.xx.xx','root','xxxx')
True
>>> s.sendline('uptime')
7
>>> print s.before
unset PROMPT_COMMAND
[root@iZ2594ysug5Z ~]# PS1='[PEXPECT]\$ ' >>> s.prompt()
True
>>> print s.before
uptime
11:24:34 up 8 days, 21:02, 2 users, load average: 0.00, 0.00, 0.00 >>> s.logout()
在使用 expect() 时,由于 Pexpect 是不断从缓冲区中匹配,如果想匹配行尾不能使用 “$” ,只能使用 “\r\n”代表一行的结束。 另外其只能得到最小匹配的结果,而不是进行贪婪匹配,例如 child.expect ('.+') 只能匹配到一个字符。
6. logfile
logfile:
只能通过 spawn 类的构造函数指定。在 spawn 类的构造函数通过参数指定 logfile 时,表示开启或关闭 logging 。所有的子程序的 input 和 output 都会被 copy 到指定的 logfile 中。设置 logfile 为 None 表示停止 logging,默认就是停止 logging 。设置 logfile 为 sys.stdout,会将所有东西 echo 到标准输出。
logfile_read和logfile_send:
logfile_read:只用来记录 python 主程序接收到 child 子程序的输出,有的时候你不想看到写给 child 的所有东西,只希望看到 child 发回来的东西。 logfile_send:只用来记录 python 主程序发送给 child 子程序的输入 logfile、logfile_read 和 logfile_send 何时被写入呢? logfile、logfile_read 和 logfile_send 会在每次写 write 和 send 操作后被 flush 。
调用 send 后,才会往 logfile 和 logfile_send 中写入,sendline/sendcontrol/sendoff/write/writeline 最终都会调用 send,所以 sendline 后 logfile 中一定有内容了,只要此时 logfile 没有被 close 。
调用 read_nonblocking 后,才会往 logfile 和 logfile_read 中写入,expect_loop 会调用 read_nonblocking,而 expect_exact 和 expect_list 都会调用 expect_loop,expect 会调用 expect_list,所以 expect 后 logfile 中一定有内容了,只要此时 logfile 没有被 close 。
python的pexpect模块的更多相关文章
- python之pexpect模块
最近在看<Python自动化运维技术与最佳实战>这本书,学到了一个运维中用到的模块:pexpect 下面是其定义: Pexpect 是一个用来启动子程序并对其进行自动控制的 Python ...
- [python]使用pexpect模块进行批量scp
#!/usr/bin/env python# -*- coding: utf-8 -*- #wangxiaofei #awcloud自动化测试 import time,osimport threadi ...
- 8.python 系统批量运维管理器之pexpect模块
小插曲 前几节讲了paramiko模块,但是pexpect模块的功能几乎跟paramiko一样,先来分析一下: 1.各自介绍 pexpect是一个通过启动子程序,使用正则表达式对程序输出做出特定响应, ...
- Python中的Pexpect模块的简单使用
Pexpect 是一个用来启动子程序并对其进行自动控制的 Python 模块. Pexpect 可以用来和像 ssh.ftp.passwd.telnet 等命令行程序进行自动交互.以下所有代码都是在K ...
- Pexpect模块的安装
Pexpect模块的安装 下载地址:https://pypi.python.org/pypi/pexpect/ 解压后在目录下运行:python ./setup.py install (必须是root ...
- python之常用模块4
pyinotify模块 pip3 install pyinotify pyinotify提供的事件: 事件标志 事件含义 IN_ACCESS 被监控项目或者被监控目录中的文件被访问,比如一个文件被读取 ...
- python的pexpect详解
Pexpect 是一个用来启动子程序并对其进行自动控制的纯 Python 模块. Pexpect 可以用来和像 ssh.ftp.passwd.telnet 等命令行程序进行自动交互.继第一部分< ...
- pexpect模块
pexpect用来启动子程序,使用正则表达式对程序输出做出特定响应,以此实现与其自动交互的python模块,当然我们可以使用他来做ssh登陆,ssh模块登陆还有一个基于python实现远程连接,用于s ...
- python的库有多少个?python有多少个模块?
这里列举了大概500个左右的库: ! Chardet字符编码探测器,可以自动检测文本.网页.xml的编码. colorama主要用来给文本添加各种颜色,并且非常简单易用. Prettytable主 ...
随机推荐
- c#笔记2019-01-06
using System; using System.Collections.Generic; using System.Linq; using System.Text; /*2019-01-06C# ...
- Linux之crontab定时任务
****crontab简介**** 简而言之呢,crontab就是一个自定义定时器. ****crontab配置文件**** 其一:/var/spool/cron/ 该目录下存放的是每个用户(包括ro ...
- float.h
float.h 一背景知识 浮点算术非常复杂 很多小的处理器在硬件指令方面甚至不支持浮点算术 其他的则需要一个独立的协处理器来处理这种运算 只有最复杂的计算机才在硬件指令集中支持浮点运算 ...
- php 修改
<?php$id = $_GET['id'];$db = new mysqli("localhost","root","root",& ...
- 牛腩新闻发布系统(二):SQLHelper重构(二)
导读:在上一篇博客中,介绍了简单的SQLHelper重构,即数据库链接,打开和关闭链接的优化等.现在,将介绍参数化查询和执行命令类型的改造. 一.必要性 1,参数化查询 在上篇博客中,在查询的时候,仅 ...
- 九度oj 题目1030:毕业bg
题目描述: 每年毕业的季节都会有大量毕业生发起狂欢,好朋友们相约吃散伙饭,网络上称为“bg”.参加不同团体的bg会有不同的感觉,我们可以用一个非负整数为每个bg定义一个“快乐度”.现给定一个b ...
- 【NOIP2014】伤感·伤感·伤感
Day <0 虽说初三的时候考过一次提高组,而且还考得不错,但自己还是挺看重这次NOIP的[你想想旁边两大神级别人物在死命刷题,蒟蒻怎敢颓废]于是切完所有复赛题后又做了好多好多次模拟赛,状态自己 ...
- [luoguP2221] [HAOI2012]高速公路(线段树)
传送门 考虑每一段对答案的贡献 用每一段的左端点来表示当前这一段,那么区间就变成了[1,n-1] 如果询问区间[l,r],其中一个点的位置为x,则它对答案的贡献为(x-l)*(r-x)*s[x](s[ ...
- USACO Longest Prefix
题目大意:给出一个长字符串,问最长的前缀,使得这个前缀能用给出的一些元素组合而成 思路:暴力dp,dp[i]表示长度为i的前缀能否被表示 /*{ ID:a4298442 PROB:prefix LAN ...
- spring之Annotation
spring除了提供了@Autowired,还提供了以下几类annotation. 1.@Component, @Repository, @Service, @Controller @Reposito ...