bosari
bosari

Reputation: 2000

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

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.

Upvotes: 5

Views: 2140

Answers (1)

Kons
Kons

Reputation: 94

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()

Upvotes: 2

Related Questions