本例子使用pexpet模塊與bash進行簡單交互秋忙,但要求輸入密碼時个榕,輸入設(shè)置好的密碼萤厅。
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") # 獲取管理員權(quán)限
# 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() # 關(guān)閉