Python 子进程无法调用 "ssh"
Python subprocess can't call "ssh"
我正在研究使用子进程模块从 Python 发送 shell 命令,特别是 ssh
。以下是准系统示例:
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()}")
这应该 return 来自 stdout 的 ssh 命令帮助,而不来自 stderr。但是,我得到:
stdout:
stderr: 'ssh' is not recognized as an internal or external command,
operable program or batch file.
我已经尝试过其他命令,例如 echo
和 cd
,并且它们工作正常。在 shell 中手动键入命令时,我也可以使用 ssh
,但是当我尝试通过子进程执行时它失败了。目录 C:\Windows\System32\OpenSSH
确实存在于我的计算机上(它包含 ssh.exe
),但由于某些奇怪的原因,我无法使用子进程 cd 到它。
如果重要的话,子进程正在使用命令提示符,cmd.exe
,因为它似乎是默认设置。
感谢任何帮助。谢谢!
-- 根据评论进行编辑--
- 使用绝对路径
C:/Windows/System32/OpenSSH/ssh.exe
不起作用,并通过 stderr 给出 The system cannot find the path specified
。 OpenSSH
文件夹似乎对 Python 通过子进程 不可见
os.environ[PATH]
包含 C:/Windows/System32/
和 C:/Windows/System32/OpenSSH/
- 运行 它与
shell=False
(使用绝对路径或仅使用 ssh
)在 Python 中引发错误:FileNotFoundError: [WinError 2] The system cannot find the file specified
你说 C:\Windows\System32\OpenSSH\ssh.exe
存在,但是当 运行 来自 Python 时找不到它。这可能是安装了 32 位版本 Python 而不是 64 位版本的结果。
如果路径存在于其他地方,但不存在于 Python,那往往会牵连到 the file system redirector。 Python 可能会在您告诉它查看 C:\Windows\System32
时看到 C:\Windows\SysWOW64
。我建议卸载你拥有的任何 Python,并明确安装 64 位版本,这样它就不会受到重定向器的影响,并且看到“真实的”System32
.
我正在研究使用子进程模块从 Python 发送 shell 命令,特别是 ssh
。以下是准系统示例:
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()}")
这应该 return 来自 stdout 的 ssh 命令帮助,而不来自 stderr。但是,我得到:
stdout:
stderr: 'ssh' is not recognized as an internal or external command,
operable program or batch file.
我已经尝试过其他命令,例如 echo
和 cd
,并且它们工作正常。在 shell 中手动键入命令时,我也可以使用 ssh
,但是当我尝试通过子进程执行时它失败了。目录 C:\Windows\System32\OpenSSH
确实存在于我的计算机上(它包含 ssh.exe
),但由于某些奇怪的原因,我无法使用子进程 cd 到它。
如果重要的话,子进程正在使用命令提示符,cmd.exe
,因为它似乎是默认设置。
感谢任何帮助。谢谢!
-- 根据评论进行编辑--
- 使用绝对路径
C:/Windows/System32/OpenSSH/ssh.exe
不起作用,并通过 stderr 给出The system cannot find the path specified
。OpenSSH
文件夹似乎对 Python 通过子进程 不可见
os.environ[PATH]
包含C:/Windows/System32/
和C:/Windows/System32/OpenSSH/
- 运行 它与
shell=False
(使用绝对路径或仅使用ssh
)在 Python 中引发错误:FileNotFoundError: [WinError 2] The system cannot find the file specified
你说 C:\Windows\System32\OpenSSH\ssh.exe
存在,但是当 运行 来自 Python 时找不到它。这可能是安装了 32 位版本 Python 而不是 64 位版本的结果。
如果路径存在于其他地方,但不存在于 Python,那往往会牵连到 the file system redirector。 Python 可能会在您告诉它查看 C:\Windows\System32
时看到 C:\Windows\SysWOW64
。我建议卸载你拥有的任何 Python,并明确安装 64 位版本,这样它就不会受到重定向器的影响,并且看到“真实的”System32
.