You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Paramiko连接SSH:如何检测服务器返回特定字符串后断开

用Paramiko检测SSH连接时的服务器断开提示及PTY问题解决

一、检测"container not found"断开情况

终端连接时服务器返回该字符串后断开,说明服务器在建立SSH会话后会立即发送这条提示并关闭连接。用Paramiko时,默认的exec_command可能来不及读取这条消息就触发断开异常,所以需要先获取交互Shell读取初始输出:

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)

try:
    ssh.connect("my.server.com", 22, "userfoo", key_filename="/home/gameveloster/.ssh/id_ed25519")
    
    # 启动交互Shell,读取服务器初始发送的消息
    shell = ssh.invoke_shell()
    shell.settimeout(5)  # 设置超时,避免无限等待
    
    # 读取所有可用输出
    initial_output = ""
    while shell.recv_ready():
        initial_output += shell.recv(1024).decode()
    
    # 检测目标字符串
    if "container not found" in initial_output:
        print("服务器返回container not found,连接已被关闭")
        ssh.close()
    else:
        # 正常执行命令
        stdin, stdout, stderr = ssh.exec_command('ls', get_pty=True)
        print("命令输出:", stdout.readlines())
        print("错误输出:", stderr.readlines())
        
except paramiko.SSHException as e:
    print(f"SSH连接异常: {str(e)}")
    # 检查连接状态
    if ssh.get_transport() and not ssh.get_transport().is_active():
        print("连接已被服务器主动关闭")
except Exception as e:
    print(f"其他异常: {str(e)}")
finally:
    # 确保连接关闭
    if ssh.get_transport() and ssh.get_transport().is_active():
        ssh.close()

二、解决"Error: Your SSH client doesn't support PTY"问题

这个错误是因为服务器要求SSH会话必须分配PTY(伪终端),而exec_command默认不启用。只需在调用时添加get_pty=True参数:

stdin, stdout, stderr = ssh.exec_command('ls', get_pty=True)

如果用交互Shell执行命令,也可以直接发送命令并读取输出:

shell.send("ls\n")
# 等待输出(可根据实际情况调整等待时间)
import time
time.sleep(1)
output = ""
while shell.recv_ready():
    output += shell.recv(1024).decode()
print(output)

内容的提问来源于stack exchange,提问作者gameveloster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 02:22:40