Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

windows - Python subprocess can't call "ssh"

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You say C:WindowsSystem32OpenSSHssh.exe exists, but that it's not found when running from Python. This is likely a result of having a 32 bit version of Python installed, rather than a 64 bit version.

If the path exists elsewhere, but not for Python, that would tend to implicate the file system redirector. Python is probably seeing C:WindowsSysWOW64 when you tell it to look in C:WindowsSystem32. I'd recommend uninstalling whatever Python you have, and explicitly installing a 64 bit version, so it isn't affected by the redirector, and sees the "real" System32.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...