使用Python的pexpet與bash進行簡單交互

本例子使用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() # 關閉
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容