ssh not recognized as a command when executed from python using subprocess?

為{幸葍}努か 提交于 2020-06-15 04:26:26

问题


This is my code -

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)

and this is the error I'm getting-

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

Not sure what I'm doing wrong over here. Also, I haven't mentioned any port. All I want is to use subprocess and connect to remote server, execute a simple command like ls. Python version is 3.x.


回答1:


Apparently this happens in python3. Workaround found at this link: 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()


来源:https://stackoverflow.com/questions/51156884/ssh-not-recognized-as-a-command-when-executed-from-python-using-subprocess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!