Python模块pexpect安装及使用流程
作者:二进制杯莫停 发布时间:2023-04-19 05:41:29
标签:Python,模块,pexpect
一、pexpect模块介绍
Pexpect使Python成为控制其他应用程序的更好工具。可以理解为Linux下的expect的Python封装,通过pexpect我们可以实现对ssh,ftp,passwd,telnet等命令行进行自动交互,而无需人工干涉来达到自动化的目的
二、Pexpect的安装
#python2
pip install pexpect
#python3
pip3 install pexpect
三、pexpect的核心组件
3.1 spawn类
3.1.1 简介
是Pexpect库的主要对象即接口类
用于启动和控制子程序
3.1.2 使用流程
建立spawn类的实例,传入要运行的命令。
调用spawn类的实例方法,与子命令交互。
通过交互的信息,完成要实现的相关功能。
3.1.3 构造方法参数
参数 | 说明 |
---|---|
command | 任何系统可执行的命令 参数可直接放入command 不直接支持管道、通配符、标志输入、输出、错误重定向 |
args=[] | 专门将command命令的参数放入这个列表中 以 '/bin/bash',['-c','cat test | grep gree'] 形式实现管道、通配符、标志输入、输出、错误重定向等功能 |
timeout=30 | 超出时间,抛出错误 |
maxread=2000 | 从TTY读取信息最大缓冲区 |
logfile=None | 指定日志文件,可指定为sys.stdout |
cwd=None | 指定命令运行时的当前目录 |
env=None | 指定命令运行时环境变量有哪些 |
encoding=None | 命令运行时,信息编码 |
codec_errors=‘strict’ | 编码转换时的转向 |
(1)command
>>> import pexpect
>>> child = pexpect.spawn('ls')
>>> child.expect(pexpect.EOF)
0
>>> print(child.before.decode())
get-pip.py nohup.out stop-ssl-dos.sh
index.html Python-2.7.18 ssl_flood.sh
>>> child = pexpect.spawn('ls -l /home')
>>> child.expect(pexpect.EOF)
0
>>> print(child.before.decode())
total 12
drwxr-xr-x 12 root root 4096 Dec 15 14:52 files
drwxr-xr-x 10 root root 4096 Aug 13 2020 opt
drwxr-xr-x 2 root root 4096 Jul 27 2017 users
# 不支持管道、通配符、标志输入、输出、错误重定向
>>> child = pexpect.spawn('ls -l | grep Python')
>>> child.expect(pexpect.EOF)
0
>>> print(child.before.decode())
/bin/ls: cannot access |: No such file or directory
/bin/ls: cannot access grep: No such file or directory
/bin/ls: cannot access Python: No such file or directory
(2)args=[]
# []传入参数列表
>>> child = pexpect.spawn('ls',args=['-l','/home'])
>>> child.expect(pexpect.EOF)
0
>>> print(child.before.decode())
total 12
drwxr-xr-x 12 root root 4096 Dec 15 14:52 files
drwxr-xr-x 10 root root 4096 Aug 13 2020 opt
drwxr-xr-x 2 root root 4096 Jul 27 2017 users
# 实现管道、通配符、标志输入、输出、错误重定向等功能
>>> child = pexpect.spawn('/bin/bash',['-c','ls -al | grep Python'])
>>> child.expect(pexpect.EOF)
0
>>> print(child.before.decode())
drwxr-xr-x 18 1000 1000 4096 Feb 9 20:31 Python-2.7.18
(5)logfile=None
打开文件
>>> f = open('log.txt','wb')
>>> child = pexpect.spawn('ls -l /home', logfile=f)
>>> child.expect(pexpect.EOF)
0
>>> f.close()
>>> exit()
[root@xxxx-2021 ~]# cat log.txt
total 12
drwxr-xr-x 12 root root 4096 Dec 15 14:52 files
drwxr-xr-x 10 root root 4096 Aug 13 2020 opt
drwxr-xr-x 2 root root 4096 Jul 27 2017 users
在终端直接显示
>>> f = open('log.txt','wb')
>>> child = pexpect.spawn('ls -l /home', logfile=f)
>>> child.expect(pexpect.EOF)
0
>>> f.close()
>>> exit()
[root@xxxx-2021 ~]# cat log.txt
total 12
drwxr-xr-x 12 root root 4096 Dec 15 14:52 files
drwxr-xr-x 10 root root 4096 Aug 13 2020 opt
drwxr-xr-x 2 root root 4096 Jul 27 2017 users
(6)cwd=None
>>> child = pexpect.spawnu('ls -al', logfile=sys.stdout, cwd='/home')
>>> child.expect(pexpect.EOF)
total 20
drwxr-xr-x 5 root root 4096 Jul 27 2017 .
drwxr-xr-x 28 root root 4096 Dec 16 07:56 ..
drwxr-xr-x 12 root root 4096 Dec 15 14:52 files
drwxr-xr-x 10 root root 4096 Aug 13 2020 opt
drwxr-xr-x 2 root root 4096 Jul 27 2017 users
0
>>>
3.1.4 基本属性和方法
描述 | 说明 |
---|---|
基本方法 | expect(pattern,timeout=-1) 注:仅列出主要参数- pattern:可以为字符串、正则表达式、EOF、TIMEOUT,或者是以上类型的列表。用于匹配子命令返回结果 - 从子命令返回结果中进行匹配,若只提供字符串等非列表,匹配成功返回0;若提供列表,则返回匹配成功的列表序号;匹配失败则会引发异常; - 匹配事项: (1)匹配的方式是从返回信息中逐个字符读出进行匹配 (2)pattern为列表时,从左至右哪个最先匹配到就匹配哪个 (3)可以对结果进行多次匹配,但只能从前往后,前边已搜索匹配的内容不会再进行匹配 (4)匹配时自动应用re.DOTALL正则选项。( .+ 会匹配所有字符,.* 返回空字符)。(5)匹配行尾用 '\r\n' (无法用$ 匹配行尾)- timeout默认为-1时,使用默认的超时期限;设置为None时,将阻塞至返回信息 sendline(s='') |
基本属性 | before:匹配点之前的文本 after:匹配成功的内容 match:已匹配的匹配对象,匹配失败为None |
特殊匹配 | pexpect.EOF pexpect.TIMEOUT 它们实际是两个异常类 |
(1)expect()连续匹配
# 连续匹配
>>> child = pexpect.spawn('ls -l')
>>> child.expect(pexpect.EOF)
0
>>> print(child.before)
total 8
-rw-r--r-- 1 root root 0 Feb 21 19:18 log.txt
drwxr-xr-x 2 root root 4096 Feb 21 19:18 test
drwxr-xr-x 2 root root 4096 Feb 21 19:19 tttt
>>>
>>> child = pexpect.spawn('ls -l')
>>> child.expect('test')
0
>>> print(child.after)
test
>>> child.expect('ttt')
0
>>> print(child.after)
ttt
>>>
# 连续匹配 列表形式
>>> child = pexpect.spawn('ls -l')
>>> child.expect('test')
0
>>> print(child.after)
test
>>> child.expect('ttt')
0
>>> print(child.after)
ttt
>>>
>>> child = pexpect.spawn('ls -l')
>>> child.expect('test')
0
>>> child.expect(['test','ttt'])
1 # 1为ttt的列表索引,因为此前已经匹配过test,文件游标不会再匹配(test在前,tttt在后)
>>>
(2)sendline(s=’’)
bash展示
[root@xxxx-2021 ~]# nslookup
> https://www.jd.com/
Server:10.138.48.2
Address:10.138.48.2#53
Non-authoritative answer:
*** Can't find https://www.jd.com/: No answer
>
使用sendline实现以上命令行功能:
>>> import pexpect
>>> child = pexpect.spawn('nslookup')
>>> child.expect('>')
0
>>> child.sendline('https://www.jd.com/')
20
>>> child.expect('>')
0
>>> print(child.before.decode())
https://www.jd.com/
Server:10.138.48.2
Address:10.138.48.2#53
Non-authoritative answer:
*** Can't find https://www.jd.com/: No answer
>>>
3.1.5 其他发送信息的方法
方法 | 描述 |
---|---|
send(s) | 类似于sendline(),只发送字符串给子程序; 不添加回车符(换行符); 打开了日志,则会添加到日志中; 返回已发送字节数; |
write(s) | 同send()方法,但无返回值; |
writelines(sequense) | 调用write()方法,将序列中内容发送 |
sendcontrol(char) | 发送类似ctrl+d、ctrl+d等组合键 |
sendof() | 发送一个结束符,一般用于确认上一次发送内容缓冲结束 |
sendintr() | 发送退出信号 |
3.1.6 其他获取结果的方法
方法 | 描述 |
---|---|
expect_exact() | 用法与expect()方法相同,匹配速度更快; 除pattern不能用正则表达式 |
expect_list() | 匹配列表只用已编译正则表达式和EOF、TIMEOUT; 提高匹配速度; expect()方法是通过它工作的 |
read(size=-1) | 从子程序输出中读取指定量数据。 size为-1时读取时直到EOF(当子程序退出后使用) |
readline(size=-1) | -1时直接读取一行数据; 0时返回为空; 其他值时被忽略,返回一行; |
# send方法
>>> child = pexpect.spawn('nslookup')
>>> child.expect('>')
0
>>> child.send('www.baidu.com')
13
>>> child.send('\n')
1
>>> child.expect('>')
0
>>> print(child.before.decode())
www.baidu.com
Server:10.138.48.2
Address:10.138.48.2#53
Non-authoritative answer:
www.baidu.comcanonical name = www.xxx.com.
Name:www.xxx.com
Address: 100.59.200.6
Name:www.xxx.com
Address: 100.59.200.7
# write方法
child.write('www.baidu.com\n')
# writelines方法
child.writelines(['www.baidu.com','\n'])
# sendintr方法 -- False表示子程序已经结束了
>>> child.sendintr()
>>> child.isalive()
False
3.1.7 其他常用方法
方法 | 描述 |
---|---|
compile_pattern_list(patterns) | 编译列表每一项的正则表达式; 当多次应用expect匹配时,每次会先对其列表实行编译后匹配; 为了提高效率,可以预先调用它进行编译; 之后直接使用expect_list()方法进行匹配 |
eof() | 抛出过EOF错误,则返回真。 |
interact(escape_character=’\x\d’, input_filter=None, output_filter=None) | 实现子程序和用户直接交互; 开启了日志,输入和输出会记录在日志文件中; input_filter和output_filter用于对输入和输出进行过滤;传入的应是接受字符串参数并返回字符串的一个函数; 默认退出键为 ctrl+] |
3.1.8 控制子程序方法
方法 | 描述 |
---|---|
kill(sig) | 通过给子程序发送信号(signal); |
来源:https://blog.csdn.net/weixin_43999327/article/details/123050864
0
投稿
猜你喜欢
- RPC是什么?所谓RPC(remote procedure call 远程过程调用)框架实际是提供了一套机制,使得应用程序之间可以进行通信,
- Linux 自动备份oracle数据:曾经有个同事,来回操作开发和生产的数据库,结果误删了生产的数据库,那种心情我想不是一般人能理解的,虽然
- 这系列文章将介绍一下Oracle的基础知识,将会使用docker下运行的oracle11g的精简版进行说明。这篇文章介绍一下oracle的版
- 前言sort包中实现了3种基本的排序算法:插入排序.快排和堆排序.和其他语言中一样,这三种方式都是不公开的,他们只在sort包内部使用.所以
- tensorflow里面给出了一个函数用来读取图像,不过得到的结果是最原始的图像,是咩有经过解码的图像,这个函数为tf.gfile.Fast
- 本文和大家重点讨论一下Perl split函数的用法,Perl中的一个非常有用的函数是Perl split函数-把字符串进行分割并把分割后的
- asp判断网址格式是否合法代码 具体实现办法见下列代码:<% function checki
- 写在前面的话:此篇还是asp相关的,相信玩ASP的都有这个感觉,当数据有5万多条时-------just like音乐网,要调用最新的10条
- a. 如果欲使用gb2312编码,那么php要输出头:header(“Content-Type: text/html; charset=gb
- 交互设计师的一项重要工作就是进行产品原型设计(Prototype Design)。而产品原型设计最基础的工作,就是画出站点的大体wirefr
- 主要原理:调整dicom的窗宽,使之各个像素点上的灰度值缩放至[0,255]范围内。使用到的python库:SimpleITK下面是一个将d
- 最近对 Range 和 Selection 比较感兴趣。基本非 IE 的浏览器都支持 DOM Level2 中的 Range,而 IE 中仅
- asp压缩access数据库,具体asp代码见下: Class DatabaseTools &n
- 除了在 Error 对象和 Errors 集合中说明的提供者错误之外,ADO 本身也将错误返回到运行时环境的异常处理机制之中。使用
- 说到网络产品,离不开的话题就是用户,就像传统行业的消费者。人是复杂的,网民的用户行为更加复杂,用户和用户是不一样的,或者说,每个用户都不一样
- PDO::setAttributePDO::setAttribute — 设置属性(PHP 5 >= 5.1.0, PECL pdo
- 本文实例讲述了PHP使用flock实现文件加锁的方法。分享给大家供大家参考。具体分析如下:flock在官方文档里的解释是:flock() 允
- 最近尝试了mysql的最新版本5.5.581.最新发布的mysql 5.5.8没有适合solaris 9的版本;这个在安装时需要注意2.它发
- 也许你听说过Hibernate的大名,但可能一直不了解它,也许你一直渴望使用它进行开发,那么本文正是你所需要的!在本文中,我向大家重点介绍H
- 本文实例为大家分享了JSP使用commons-fileupload实现文件上传代码,供大家参考,具体内容如下1、准备:将commons-fi