看完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.