繁体   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