簡體   English   中英

如何使用 python 在 shell 中讀取控制台 output?

[英]how to read console output in shell using python?

我正在嘗試閱讀我的 shell 的 output 即我想知道該命令是否已完全執行或要求輸入密碼或任何其他輸入,因為對我來說,每次都要求輸入密碼並不是強制性的。 它有時會要求輸入密碼。

您正在尋找的模塊是pexpect https://pexpect.readthedocs.io/en/stable/

例如:

import pexpect

child = pexpect.spawn('ssh -l %s %s'%(user, host))

i = child.expect([pexpect.TIMEOUT, SSH_NEWKEY, '[Pp]assword: '])
if i == 0: # Timeout
    print('ERROR!')
    print('SSH could not login. Here is what SSH said:')
    print(child.before, child.after)
    sys.exit (1)
if i == 1: # SSH does not have the public key. Just accept it.
    child.sendline ('yes')
    child.expect ('[Pp]assword: ')
child.sendline(password)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM