本例子使用pexpet模塊與bash進行簡單交互,但要求輸入密碼時,輸入設置好的密碼。
import pexpect
PROMPT = "[$#]" # 正則匹配$或#
# get shell bash
def getBash():
child = pexpect.spwn("/bin/bash")
child.expect(PROMPT) # 等待用戶輸入
return child
child = getBash()
# set log file.
log = file('./demo.log', 'w')
child.logfile = log
child.sendline("su") # 獲取管理員權限
# when bash need password
child.expect("password") # 攔截到需要輸入密碼
# enter you password
child.sendline('yourPassword')
child.expect(PROMPT) # 等待用戶輸入
child.send("your command") # 輸入你的命令
......
output = child.read() # 讀取bash中的輸出
print(output)
child.close() # 關閉