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()}
stderr: {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:WindowsSystem32OpenSSH
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 gives The system cannot find the path specified
via stderr. The OpenSSH
folder doesn't seem to be visible to Python through subprocess
os.environ[PATH]
contains both C:/Windows/System32/
and C:/Windows/System32/OpenSSH/
- Running it with
shell=False
(either with the absolute path or just with ssh
) raises an error in Python: FileNotFoundError: [WinError 2] The system cannot find the file specified
question from:
https://stackoverflow.com/questions/65928671/python-subprocess-cant-call-ssh 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…