简体   繁体   English

为什么我不能使用subprocess.Popen与SSH交互?

[英]Why can't I interact with SSH using subprocess.Popen?

I'm trying to interact with SSH using Python's subprocess library. 我正在尝试使用Python的subprocess库与SSH进行交互。 Here's my current code: 这是我当前的代码:

import subprocess
import time
proc = subprocess.Popen(["ssh", "-tt", "user@host"],
                        stdout=subprocess.PIPE, stdin=subprocess.PIPE)
time.sleep(10)
proc.stdin.write(b"ls\n")
while True:
    next_line = proc.stdout.readline()
    if next_line != '':
        print(next_line.decode("utf-8"), end='')
    else:
        time.sleep(.01)

When I run it, I get the usual SSH security banner, but nothing else. 当我运行它时,我得到了通常的SSH安全性标语,但除此之外没有别的。 I log in via public key and have already added the host to my known_hosts list, so I would imagine authentication shouldn't be an issue. 我通过公共密钥登录,并且已经将主机添加到我的known_hosts列表中,因此我认为身份验证应该不是问题。 By changing ls to a command to write text to a file, I have confirmed that no commands are "going through." 通过将ls更改为将文本写入文件的命令,我已经确认没有命令在“通过”。 What is the problem, and how can I fix it? 有什么问题,我该如何解决?

You may need to call proc.stdin.flush() . 您可能需要调用proc.stdin.flush() More generally, you should use Paramiko instead, which is a Python library for SSH directly, rather than using Popen for this. 更一般而言,您应该改为使用Paramiko (这是直接用于SSH的Python库),而不是为此使用Popen。

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

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