expect學習日誌-Python pexpect模塊

看完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.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章