Plumbum SshMachine无法通过跳板机连接,但原生命令可成功
问题:通过Plumbum SshMachine跳板连接Linux机器失败(Windows本地)
环境信息
- 本地系统:Windows
- 远程机器:两台Linux(
portal_machine跳板机、final_machine目标机) - 已配置SSH密钥:本地↔
portal_machine、本地↔final_machine、portal_machine↔final_machine
可成功的连接方式
1. CMD直接执行SSH命令
ssh {username}@{final_machine} -oProxyCommand="ssh -W {final_machine}:22 {username}@{portal_machine}"
2. Plumbum调用本地SSH命令
import plumbum ssh_command = plumbum.local["ssh"][f"{username}@{final_machine}", "-o", f"ProxyCommand=ssh -W {final_machine}:22 {username}@{portal_machine}"] ssh_command()
失败的连接方式(SshMachine对象)
使用Plumbum的SshMachine类连接时失败,代码如下:
import plumbum plumbum.SshMachine(final_machine, user=username, ssh_opts=[fr'-o ProxyCommand="ssh -W {final_machine}:22 {username}@{portal_machine}"'])
报错信息
Return code: | None Command line: | 'true ' Host: | {final machine} Stderr: | CreateProcessW failed error:2
已尝试的操作
- 将SSH路径指定为
C:\Windows\System32\OpenSSH\ssh.exe,问题依旧 - 直接通过
SshMachine连接portal_machine可正常工作
调试建议
拆分SSH选项参数:Plumbum的
ssh_opts需要将每个选项拆分为独立元素,不要把-o和后续参数合并成单个字符串。修改代码为:plumbum.SshMachine(final_machine, user=username, ssh_opts=[ '-o', f'ProxyCommand=ssh -W {final_machine}:22 {username}@{portal_machine}' ])原代码的参数合并写法会导致Plumbum解析错误,Windows的CreateProcessW无法正确识别命令结构。
移除ProxyCommand中的引号:Windows OpenSSH环境下,ProxyCommand内部的引号可能引发解析异常,尝试去掉引号后再测试。
显式指定SSH路径到SshMachine:初始化
SshMachine时通过ssh_cmd参数传入完整SSH路径,避免路径解析偏差:plumbum.SshMachine(final_machine, user=username, ssh_cmd='C:\\Windows\\System32\\OpenSSH\\ssh.exe', ssh_opts=[ '-o', f'ProxyCommand=ssh -W {final_machine}:22 {username}@{portal_machine}' ])开启Plumbum调试日志:添加日志输出,查看实际执行的SSH命令细节,对比CMD成功命令的格式差异:
import logging logging.basicConfig(level=logging.DEBUG)单独测试ProxyCommand命令:在CMD中执行
ssh -W {final_machine}:22 {username}@{portal_machine},确认跳板隧道可正常建立,排除跳板机本身的问题。
内容的提问来源于stack exchange,提问作者ACarter
相关产品推荐
相关产品推荐

