简体   繁体   English

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

[英]Real time output using login shell command from Python3

I'm trying to get the output of a subprocess to prompt for a login then continue with the rest of the script once logged in. I can get it to prompt for the login, but after entering my username and password I get the following error: 我试图获取子流程的输出以提示登录,然后在登录后继续执行脚本的其余部分。我可以获取提示输入登录名的提示,但是输入用户名和密码后出现以下错误:

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.

Below is the script: 下面是脚本:

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()

When I normally execute the command from the shell it returns nothing after logging in. 当我正常从外壳执行命令时,登录后不返回任何内容。

I found another way around this situation. 我找到了解决这种情况的另一种方法。 Instead of passing the real-time output I prompted for the the user's username and password information and inserted that information into the command. 我没有传递实时输出,而是提示用户输入用户名和密码信息,并将该信息插入命令中。 The below function works: 以下功能有效:

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM