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

本例子使用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)閉
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容