python - 使用子进程从 python 执行时,ssh 不被识别为命令?

标签 python python-3.x ssh subprocess

这是我的代码 -

import subprocess
import sys

HOST="xyz3511.uhc.com"
# Ports are handled in ~/.ssh/config since we use OpenSSH
COMMAND="uptime"

ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
                       shell=True,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
    error = ssh.stderr.readlines()
    print (sys.stderr, "ERROR: %s" % error)
else:
    print (result)

这是我遇到的错误-

ERROR: [b"'ssh' is not recognized as an internal or external command,\r\n", b'operable program or batch file.\r\n'].

不确定我在这里做错了什么。另外,我没有提到任何端口。我只想使用子进程并连接到远程服务器,执行一个简单的命令,如 ls。 Python 版本为 3.x。

最佳答案

显然这发生在 python3 中。 在此链接中找到解决方法: https://gist.github.com/bortzmeyer/1284249

system32 = os.path.join(os.environ['SystemRoot'], 'SysNative' if platform.architecture()[0] == '32bit' else 'System32')
ssh_path = os.path.join(system32, 'OpenSSH/ssh.exe')
out1, err1 = Popen([ssh_path, "pi@%s"%self.host, "%s"%cmd],
              shell=False,
              stdout=PIPE, 
              stderr=PIPE).communicate()

关于python - 使用子进程从 python 执行时,ssh 不被识别为命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51156884/

相关文章:

python-3.x - 如何在没有 shell 脚本(.sh)的情况下从 python 脚本(.py)激活虚拟环境?

python - 在前台生成一个子进程,即使在 python 退出之后

phpseclib - 我可以使用用户名、 key 和密码(不是 key 密码)进行连接吗

ssh - 为什么我的 SSH 在连接到 github 时卡在那里?

python - 使用正则表达式查找模式

python - 如何在交互模式下使用Elmo词嵌入与原始预训练模型(5.5B)

python - 调用 fork() 时,多处理导致 Python 崩溃并给出错误可能已在另一个线程中进行

python - 使用 Python 进行 zappa 调度

python - 从 django-rest 检索数据以显示在表单中

python - 在 python 中使用 str.format() 女巫类