I'm working on using the subprocess module to send shell commands from Python, specifically, ssh
. Below is a barebones sample:
import subprocess
sp = subprocess.run(["ssh"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(f"stdout: {sp.stdout.decode()} \n\nstderr: {sp.stderr.decode()}")
This should return the ssh command help from stdout, and nothing from stderr. However, I get:
stdout:
stderr: 'ssh' is not recognized as an internal or external command,
operable program or batch file.
I've tried other commands, like echo
and cd
, and those work fine. I am also able to use ssh
when manually typing the command into the shell, but it fails when I try to do it through subprocess. The directory C:\Windows\System32\OpenSSH
does exist on my computer (and it contains ssh.exe
), but for some strange reason I'm unable to cd to it using subprocess.
If it matters, subprocess is using the command prompt, cmd.exe
, as it seems to be the default.
Any help is appreciated. Thanks!
-- Edits with tests from comments --
- Using the absolute path
C:/Windows/System32/OpenSSH/ssh.exe
does not work, and givesThe system cannot find the path specified
via stderr. TheOpenSSH
folder doesn't seem to be visible to Python through subprocess os.environ[PATH]
contains bothC:/Windows/System32/
andC:/Windows/System32/OpenSSH/
- Running it with
shell=False
(either with the absolute path or just withssh
) raises an error in Python:FileNotFoundError: [WinError 2] The system cannot find the file specified