測試環境為 CentOS 8 x86_64 (虛擬機)
Pexpect 使用上蠻像之前常用的 TeraTerm Marco – https://benjr.tw/20386 , 透過 Pexpect 套件可以跟其他程式互動,基本上就3個動作
- 呼叫程式.
- 等待程式關鍵字.
- 傳送字串.
安裝所需套件.
[root@localhost ~]# pip install pexpect
[root@localhost ~]# python3 Python 3.6.8 (default, Mar 25 2022, 11:15:52) [GCC 8.5.0 20210514 (Red Hat 8.5.0-10)] on linux Type "help", "copyright", "credits" or "license" for more information.
範例參考 – https://pexpect.readthedocs.io/en/stable/api/pexpect.html
手動執行指令步驟如下:
先產生測試所需檔案.
[root@localhost ~]# touch empty.py [root@localhost ~]# ll empty.py -rw-r--r-- 1 root root 0 Mar 15 16:03 empty.py
透過 scp 複製檔案到遠端 (使用 -o StrictHostKeyChecking=no 自動同意遠端的簽章)
[root@localhost ~]# scp -o StrictHostKeyChecking=no empty.py root@192.168.31.132:/root/pepect1.py Warning: Permanently added '192.168.31.132' (ECDSA) to the list of known hosts. root@192.168.31.132's password: empty.py 100% 0 0.0KB/s 00:00
檢視遠端 IP:192.168.31.132 檔案.
[root@localhost ~]# ll pepect1.py -rw-r--r-- 1 root root 0 Mar 15 16:08 pepect1.py
透過 pexpect 完成剛剛手動步驟.
import pexpect child = pexpect.spawn('scp -o StrictHostKeyChecking=no empty.py root@192.168.31.132:/root/pepect2.py') child.expect('password:') child.sendline('111111')
檢視遠端 IP:192.168.31.132 檔案.
[root@localhost ~]# ll pepect2.py -rw-r--r-- 1 root root 0 Mar 15 16:10 pepect2.py
程式說明:
- 呼叫程式.
child = pexpect.spawn('scp -o StrictHostKeyChecking=no empty.py root@192.168.31.132:/root/pepect2.py')
- 等待程式關鍵字.
child.expect('password:')
- 傳送字串.
child.sendline('111111')
沒有解決問題,試試搜尋本站其他內容