python module "Pexpect" 的使用
Pexpect 可以用于自動化交互式程序, 例如, ssh, ftp, 模擬手動操作。
下列是Pexpect 常用的API。
-
注意:spawn , run API 只能在linux 上運行, windows 上不行,windows 用別的AP。 詳情參考官網文檔。
- run() method
# run method 用于執行一個命令并返回命令的output.
# 注意, 返回值是byte 格式
# pexpect 是類似手動操作, run method 的上下文就是當前child process 環境。
# example
import pexpect
cmd = "ssh username@localhost"
child = pexpect.spawn(cmd)
index = child.expect(".*password:")
if index == 0:
child.sendline("password") # send password
index = child.expect("DESKTOP-5C:") # 等待提示符
if index == 0:
print("congratulations") # login 成功
rst = pexpect.run("ifconfig")
print(f"rst is {rst}")
- spawn 方法
- spawn method 用于開啟一個子進程, 并返回子進程
- expect method 用于等待子進程返回pattern 字符串。
import pexpect
# start a child process with spawn
# It just echos geeksforgeeks
child = pexpect.spawn("echo hai geeksforgeeks")
# prints he matched index of string.
print(child.expect(["hai", "welcome", "geeksforgeeks", "DESKTOP"])) #
- 保存文件功能
-- 給child.logfile assign一個文件接口, 所有信息都會被保留, 包括交互的信息, 就跟手動操作是一樣的
-- 注意pexepct 的返回都是byte 格式, 所以file open format 一定要是"b" format
-- 此例子中有用到sendline 方法, send line 用法不言而明。
import pexpect
import sys
logfilehandle = open("aa.log","ab")
cmd = "ssh username@localhost"
child = pexpect.spawn(cmd)
child.logfile = logfilehandle
index = child.expect(".*password:")
if index == 0:
child.sendline("password") # send password
index = child.expect("DESKTOP-5C:")
if index == 0:
print("congratulations")
child.sendline("ifconfig")
child.sendline("echo finished")
index = child.expect("DESKTOP-5C3GASH:")
if index == 0:
print("child after:")
rst = child.before
rst_lines = rst.decode('gbk').split("\r\n")
for i in rst_lines:
print(f"---{i}")
logfilehandle.close()
posted on 2023-01-31 12:19 MissLi12138 閱讀(75) 評論(0) 收藏 舉報
浙公網安備 33010602011771號