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  阅读(23)  评论(0编辑  收藏  举报

导航