網站首頁 編程語言 正文
一、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.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表示子程序已經結束了 >>> 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
相關推薦
- 2023-02-06 C#基于時間輪調度實現延遲任務詳解_C#教程
- 2022-07-14 一文教會你用redux實現computed計算屬性_React
- 2022-12-12 python語法之通過value找key問題_python
- 2023-03-29 python中文字符如何轉url編碼_python
- 2022-11-18 Redux模塊化拆分reducer函數流程介紹_React
- 2022-07-04 C#操作配置文件app.config、web.config增刪改_C#教程
- 2022-04-22 如何讓electron收到消息發出聲音
- 2022-09-14 React?UI組件庫之快速實現antd的按需引入和自定義主題_React
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支