使用子进程从python执行时,ssh无法识别为命令?

时间:2018-07-03 14:17:06

标签: 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)

这是我得到的错误-

  

错误:   [b“'ssh'不被识别为内部或外部命令,\ r \ n”,   b'可运行的程序或批处理文件。\ r \ n']。

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

1 个答案:

答案 0 :(得分:0)

显然,这发生在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()