使用Python3的login shell命令实时输出

时间:2016-12-21 22:22:09

标签: python shell python-3.x subprocess

我正在尝试获取子进程的输出以提示登录,然后在登录后继续使用其余的脚本。我可以让它提示登录,但输入我的用户名和密码后,我得到以下错误:

Traceback (most recent call last):
  File "./login.py", line 20, in <module>
    login()
  File "./login.py", line 13, in login
    output = login_cmd.stderr.read(1)
ValueError: read of closed file.

以下是剧本:

import subprocess, sys

raidcom = '/usr/bin/raidcom'

def login(cmd=raidcom):
    login_cmd = subprocess.Popen('{cmd} -login'.format(cmd=cmd),
                                 stderr=subprocess.PIPE, shell=True)
    (output, err) = login_cmd.communicate()
    while True:
        output = login_cmd.stderr.read(1)
        if output == '' and login_cmd.poll() != None:
            break
        if output != '':
            sys.stdout.write(output)
            sys.stdout.flush()

login()

当我通常从shell执行命令时,它在登录后不返回任何内容。

1 个答案:

答案 0 :(得分:0)

我找到了解决这种情况的另一种方法。而不是传递实时输出,我提示输入用户的用户名和密码信息,并将该信息插入到命令中。以下功能有效:

import subprocess
import getpass

raidcom = '/usr/bin/raidcom'

def raidcom_login(cmd=raidcom):
    """Login to CCI and return its output."""
    horcm_user = input("Please enter your username for logging into CCI: ")
    horcm_pass = getpass.getpass("Please enter your password: ")
    try:
        login_cmd = subprocess.check_output('{cmd} -login {} {}'.format(horcm_user, horcm_pass, cmd=cmd),
                                 stderr=subprocess.PIPE, shell=True)
    except subprocess.CalledProcessError:
        print('Login failed')