Python模塊pexpect安裝及使用流程
一、pexpect模塊介紹
Pexpect使Python成為控制其他應(yīng)用程序的更好工具??梢岳斫鉃長(zhǎng)inux下的expect的Python封裝,通過pexpect我們可以實(shí)現(xiàn)對(duì)ssh,ftp,passwd,telnet等命令行進(jìn)行自動(dòng)交互,而無需人工干涉來達(dá)到自動(dòng)化的目的
二、Pexpect的安裝
#python2 pip install pexpect #python3 pip3 install pexpect
三、pexpect的核心組件
3.1 spawn類
3.1.1 簡(jiǎn)介
- 是Pexpect庫(kù)的主要對(duì)象即接口類
- 用于啟動(dòng)和控制子程序
3.1.2 使用流程
- 建立spawn類的實(shí)例,傳入要運(yùn)行的命令。
- 調(diào)用spawn類的實(shí)例方法,與子命令交互。
- 通過交互的信息,完成要實(shí)現(xiàn)的相關(guān)功能。
3.1.3 構(gòu)造方法參數(shù)
| 參數(shù) | 說明 |
|---|---|
| command | 任何系統(tǒng)可執(zhí)行的命令 參數(shù)可直接放入command 不直接支持管道、通配符、標(biāo)志輸入、輸出、錯(cuò)誤重定向 |
| args=[] | 專門將command命令的參數(shù)放入這個(gè)列表中 以 '/bin/bash',['-c','cat test | grep gree']形式實(shí)現(xiàn)管道、通配符、標(biāo)志輸入、輸出、錯(cuò)誤重定向等功能 |
| timeout=30 | 超出時(shí)間,拋出錯(cuò)誤 |
| maxread=2000 | 從TTY讀取信息最大緩沖區(qū) |
| logfile=None | 指定日志文件,可指定為sys.stdout |
| cwd=None | 指定命令運(yùn)行時(shí)的當(dāng)前目錄 |
| env=None | 指定命令運(yùn)行時(shí)環(huán)境變量有哪些 |
| encoding=None | 命令運(yùn)行時(shí),信息編碼 |
| codec_errors=‘strict’ | 編碼轉(zhuǎn)換時(shí)的轉(zhuǎn)向 |
(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
# 不支持管道、通配符、標(biāo)志輸入、輸出、錯(cuò)誤重定向
>>> 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=[]
# []傳入?yún)?shù)列表
>>> 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
# 實(shí)現(xiàn)管道、通配符、標(biāo)志輸入、輸出、錯(cuò)誤重定向等功能
>>> 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)注:僅列出主要參數(shù)- pattern:可以為字符串、正則表達(dá)式、EOF、TIMEOUT,或者是以上類型的列表。用于匹配子命令返回結(jié)果 - 從子命令返回結(jié)果中進(jìn)行匹配,若只提供字符串等非列表,匹配成功返回0;若提供列表,則返回匹配成功的列表序號(hào);匹配失敗則會(huì)引發(fā)異常; - 匹配事項(xiàng): (1)匹配的方式是從返回信息中逐個(gè)字符讀出進(jìn)行匹配 (2)pattern為列表時(shí),從左至右哪個(gè)最先匹配到就匹配哪個(gè) (3)可以對(duì)結(jié)果進(jìn)行多次匹配,但只能從前往后,前邊已搜索匹配的內(nèi)容不會(huì)再進(jìn)行匹配 (4)匹配時(shí)自動(dòng)應(yīng)用re.DOTALL正則選項(xiàng)。( .+會(huì)匹配所有字符,.*返回空字符)。(5)匹配行尾用 '\r\n'(無法用$匹配行尾)- timeout默認(rèn)為-1時(shí),使用默認(rèn)的超時(shí)期限;設(shè)置為None時(shí),將阻塞至返回信息 sendline(s='') |
| 基本屬性 | before:匹配點(diǎn)之前的文本 after:匹配成功的內(nèi)容 match:已匹配的匹配對(duì)象,匹配失敗為None |
| 特殊匹配 | pexpect.EOF pexpect.TIMEOUT 它們實(shí)際是兩個(gè)異常類 |
(1)expect()連續(xù)匹配
# 連續(xù)匹配
>>> 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
>>>
# 連續(xù)匹配 列表形式
>>> 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的列表索引,因?yàn)榇饲耙呀?jīng)匹配過test,文件游標(biāo)不會(huì)再匹配(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實(shí)現(xiàn)以上命令行功能:
>>> 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 其他發(fā)送信息的方法
| 方法 | 描述 |
|---|---|
| send(s) | 類似于sendline(),只發(fā)送字符串給子程序; 不添加回車符(換行符); 打開了日志,則會(huì)添加到日志中; 返回已發(fā)送字節(jié)數(shù); |
| write(s) | 同send()方法,但無返回值; |
| writelines(sequense) | 調(diào)用write()方法,將序列中內(nèi)容發(fā)送 |
| sendcontrol(char) | 發(fā)送類似ctrl+d、ctrl+d等組合鍵 |
| sendof() | 發(fā)送一個(gè)結(jié)束符,一般用于確認(rèn)上一次發(fā)送內(nèi)容緩沖結(jié)束 |
| sendintr() | 發(fā)送退出信號(hào) |
3.1.6 其他獲取結(jié)果的方法
| 方法 | 描述 |
|---|---|
| expect_exact() | 用法與expect()方法相同,匹配速度更快; 除pattern不能用正則表達(dá)式 |
| expect_list() | 匹配列表只用已編譯正則表達(dá)式和EOF、TIMEOUT; 提高匹配速度; expect()方法是通過它工作的 |
| read(size=-1) | 從子程序輸出中讀取指定量數(shù)據(jù)。 size為-1時(shí)讀取時(shí)直到EOF(當(dāng)子程序退出后使用) |
| readline(size=-1) | -1時(shí)直接讀取一行數(shù)據(jù); 0時(shí)返回為空; 其他值時(shí)被忽略,返回一行; |
# 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.com canonical 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表示子程序已經(jīng)結(jié)束了
>>> child.sendintr()
>>> child.isalive()
False
3.1.7 其他常用方法
| 方法 | 描述 |
|---|---|
| compile_pattern_list(patterns) | 編譯列表每一項(xiàng)的正則表達(dá)式; 當(dāng)多次應(yīng)用expect匹配時(shí),每次會(huì)先對(duì)其列表實(shí)行編譯后匹配; 為了提高效率,可以預(yù)先調(diào)用它進(jìn)行編譯; 之后直接使用expect_list()方法進(jìn)行匹配 |
| eof() | 拋出過EOF錯(cuò)誤,則返回真。 |
| interact(escape_character=’\x\d’, input_filter=None, output_filter=None) | 實(shí)現(xiàn)子程序和用戶直接交互; 開啟了日志,輸入和輸出會(huì)記錄在日志文件中; input_filter和output_filter用于對(duì)輸入和輸出進(jìn)行過濾;傳入的應(yīng)是接受字符串參數(shù)并返回字符串的一個(gè)函數(shù); 默認(rèn)退出鍵為 ctrl+] |
3.1.8 控制子程序方法

| 方法 | 描述 |
|---|---|
| kill(sig) | 通過給子程序發(fā)送信號(hào)(signal); |
到此這篇關(guān)于Python模塊之pexpect詳解的文章就介紹到這了,更多相關(guān)Python模塊pexpect 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python中使用攝像頭實(shí)現(xiàn)簡(jiǎn)單的延時(shí)攝影技術(shù)
這篇文章主要介紹了Python中使用攝像頭實(shí)現(xiàn)簡(jiǎn)單的延時(shí)攝影技術(shù),本文只是一個(gè)簡(jiǎn)單的小示例,講解了實(shí)現(xiàn)過程并給出實(shí)現(xiàn)代碼,需要的朋友可以參考下2015-03-03
保姆級(jí)官方y(tǒng)olov7訓(xùn)練自己的數(shù)據(jù)集及項(xiàng)目部署詳解
最近使用了YOLOv7訓(xùn)練自己的數(shù)據(jù)集,接下來簡(jiǎn)單記錄一下項(xiàng)目的部署,這篇文章主要給大家介紹了關(guān)于保姆級(jí)官方y(tǒng)olov7訓(xùn)練自己的數(shù)據(jù)集及項(xiàng)目部署的相關(guān)資料,需要的朋友可以參考下2022-08-08
tesserocr與pytesseract模塊的使用方法解析
這篇文章主要介紹了tesserocr與pytesseract模塊的使用方法解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08
Python去除html標(biāo)簽的幾種方法總結(jié)
這篇文章主要介紹了Python去除html標(biāo)簽的幾種方法總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01
使用python+pygame實(shí)現(xiàn)中秋節(jié)動(dòng)畫效果
馬上就要中秋節(jié)了,使用python可以實(shí)現(xiàn)中秋節(jié)動(dòng)畫效果,包括月亮、兔子和煙花嗎?當(dāng)然是可以的,那該如何實(shí)現(xiàn)呢?這篇文章我們主要使用pygame來實(shí)現(xiàn),文中有詳細(xì)的代碼示例供大家參考,需要的朋友可以參考下2023-09-09

