简体   繁体   English

Python子进程stdout.readlines()被卡住

[英]Python subprocess stdout.readlines() getting stuck

I am trying to use to python subprocess module in order to ssh to a server and then switch to a super user and then ls and print the folders in the terminal. 我试图使用python子处理模块,以便ssh到服务器,然后切换到超级用户,然后ls并在终端中打印文件夹。

My Code: 我的代码:

def sudo_Test():
    HOST = 'Host'
    PORT = '227'
    USER = 'user'
    cmd='sudo su - ec2-user;ls'

    process = subprocess.Popen(['ssh','-tt','{}@{}'.format(USER, HOST),
                            '-p',PORT,cmd],
                           shell=False,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE,
                           stdin=subprocess.PIPE)
    process.stdin.write("my_password\r\n")

    print "stuck here VVV"
    result = process.stdout.readlines()
    print "finished it"

    if not result:
        print "Im an error"
        err = process.stderr.readlines()
        print('ERROR: {}'.format(err))
    else:
        print "I'm a success"
        print result

print sudo_Test()

Console output when I run this: 运行此命令时的控制台输出:

dredbounds-computer:folder dredbound$ python terminal_test.py
stuck here VVV

For some reason the code gets stuck on the line result = process.stdout.readlines(). 由于某种原因,代码被卡在行result = process.stdout.readlines()上。 I have to cntrl+c to exit out of the terminal session when this happens. 发生这种情况时,我必须cntrl + c退出终端会话。 It works fine if I just do cmd='sudo; 如果我只是执行cmd ='sudo,它会很好地工作; ls' instead of cmd='sudo su - ec2-user;ls'.Anyone know what I'm doing wrong or how I can get this to work? ls'而不是cmd ='sudo su-ec2-user; ls'。有人知道我做错了什么或如何使它工作?

Update: I changed cmd='sudo su - ec2-user;ls' -> cmd='sudo su - ec2-user ls' in the code above. 更新:我在上面的代码中更改了cmd ='sudo su-ec2-user; ls'-> cmd ='sudo su-ec2-user ls'。 Now I am getting the following error: 现在我收到以下错误:

['password\r\n', '\r\n', '/bin/ls: /bin/ls: cannot execute binary   file\r\n']

I'm not sure why it thinks ls is a binary file now, but is there anyway i can tell it that it is just a terminal command so it returns a list of directories? 我不知道为什么它现在认为ls是一个二进制文件,但是无论如何我可以告诉我那只是一个终端命令,所以它返回目录列表吗?

The problem is here: 问题在这里:

sudo su - ec2-user;ls

sudo su - ec2-user opens a shell and waits for input. sudo su - ec2-user打开一个shell并等待输入。 You need to send the shell an exit command (or close its stdin) before the shell exits and the ls command is run. 您需要在外壳程序退出并运行ls命令之前向外壳程序发送退出命令(或关闭其标准输入)。

If your goal was to run ls as user ec2-user , then try: 如果您的目标是以ec2-user身份运行ls ,请尝试:

sudo -u ec2-user ls

In other words, replace 换句话说,替换

cmd='sudo su - ec2-user;ls'

With: 带有:

cmd='sudo -u ec2-user ls'

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

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