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 方法
1 2 3 4 5 6 7 8 9 10 11 12 | - 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" ])) # |
- 保存文件功能
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 | - - 给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 阅读(58) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?