python module "Pexpect" 的使用

Pexpect 可以用于自动化交互式程序, 例如, ssh, ftp, 模拟手动操作。

下列是Pexpect 常用的API。

  • 注意:spawn , run API 只能在linux 上运行, windows 上不行,windows 用别的AP。 详情参考官网文档。
  • run() method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 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 方法
  •  保存文件功能

 

posted on   MissLi12138  阅读(58)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示