如何获取Python Paramiko SSH连接try/except的更多错误信息
获取Paramiko详细错误信息的方案
1. 捕获Paramiko特定异常
Paramiko提供了多个细分异常类,针对性捕获能得到更精准的错误原因,避免用宽泛的Exception掩盖细节:
import paramiko try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.WarningPolicy()) ssh.connect(IP, username=USER_GW, password=PSW_GW, look_for_keys=False) stdin, stdout, stderr = ssh.exec_command(command, timeout=60) output = stdout.read().decode('ascii').strip("\n") except paramiko.AuthenticationException: print("认证失败:请检查用户名或密码是否正确") except paramiko.BadHostKeyException as e: print(f"主机密钥不匹配:{str(e)}") except paramiko.SSHException as e: print(f"SSH连接或命令执行出错:{str(e)}") except Exception as e: print(f"其他未知错误:{str(e)}") finally: # 先判断对象是否初始化,避免未定义时调用close引发新异常 if 'ssh' in locals(): ssh.close() for stream in [stdin, stdout, stderr]: if stream is not None: stream.close()
2. 打印完整异常栈
使用traceback模块输出完整调用栈,能精准定位Paramiko出错的代码位置:
import traceback import paramiko try: # 你的SSH操作逻辑 except Exception as e: print("错误详情:") traceback.print_exc()
3. 读取远程命令的stderr输出
如果是远程命令执行失败,除了捕获异常,还可以读取stderr内容,获取远程端的错误信息:
stdin, stdout, stderr = ssh.exec_command(command, timeout=60) # 优先读取stderr获取命令执行错误 remote_error = stderr.read().decode('ascii').strip("\n") if remote_error: print(f"远程命令执行错误:{remote_error}") output = stdout.read().decode('ascii').strip("\n")
4. 修复finally块的隐患
当前finally块直接调用ssh.close()等操作,如果try块中ssh初始化失败(比如连接出错),会触发未定义变量的新异常,掩盖原始错误。必须先判断变量是否存在再执行关闭操作。
内容的提问来源于stack exchange,提问作者martinmistere
相关产品推荐
相关产品推荐

