expect学习日志-Python pexpect模块

Pexpect是一个纯Python模块,用于启动子应用程序,控制它们,并响应其输出中的预期模式。它类似于Don Libes的Expect,允许脚本像人类一样输入命令控制子应用,适用于自动化ssh、ftp等交互式应用程序,软件包安装,以及自动化软件测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看完expect的主要功能, 本想自己用Python对expect进行封装,方便后续直接使用Python调用,但惊喜的是网上一查,竟然发现已有人用Python实现了相关功能。模块名称是-Pexpect .

Pexpect is a pure Python module for spawning child applications; controlling them; and responding to expected patterns in their output. Pexpect works like Don Libes’ Expect. Pexpect allows your script to spawn a child application and control it as if a human were typing commands.

Pexpect can be used for automating interactive applications such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup scripts for duplicating software package installations on different servers. It can be used for automated software testing. Pexpect is in the spirit of Don Libes’ Expect, but Pexpect is pure Python. Unlike other Expect-like modules for Python, Pexpect does not require TCL or Expect nor does it require C extensions to be compiled. It should work on any platform that supports the standard Python pty module. The Pexpect interface was designed to be easy to use.

官网链接:https://pexpect.readthedocs.io/en/stable/index.html
GitHub仓库:https://github.com/pexpect/pexpect

简单示例

import pexpect

user = ' '
ip = ' '
mypassword = ''

print(user)
child = pexpect.spawn('ssh %s@%s -y' % (user, ip))
child.expect('password:')
child.sendline(mypassword)

child.expect('$')
child.sendline('sudo -s')
child.expect(':')
child.sendline(mypassword)
child.expect('#')
child.sendline('ls -la')
child.expect('#')
print(child.before)  # Print the result of the ls command.
child.sendline("echo '112' >> /home/1.txt ")
child.interact()  # Give control of the child to the user.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值