5

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.

6
  • 1
    are you able to ssh explicitely on terminal? I mean not in Python program Commented Jul 3, 2018 at 14:26
  • 3
    Are you executing this on a Windows machine which doesn't have an SSH client (with the name ssh) installed? Commented Jul 3, 2018 at 14:35
  • yes I'm using this program in windows Commented Jul 5, 2018 at 6:45
  • @alfe I'm getting the same error on a windows machine with SSH installed (ssh command works in cmd but not in subprocess) Commented Aug 6, 2019 at 14:26
  • Make sure the ssh command is found. Either set you weir Windows equivalent of the PATH variable accordingly or just use the complete path to the ssh executable instead of just ssh, i. e. something like C:\some\path\to\ssh. Commented Aug 8, 2019 at 15:12

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.