Telnetlib三种异常处理方案

1. socket.timeout 异常

触发场景
  • 网络延迟高或设备响应缓慢,导致连接或读取超时。
示例代码
python 复制代码
import telnetlib
import socket

def telnet_connect_with_timeout(host, port=23, timeout=2):
    try:
        # 设置超时时间(故意设置较短时间模拟超时)
        tn = telnetlib.Telnet()
        tn.open(host, port, timeout=timeout)
        
        # 尝试读取登录提示(可能因设备响应慢触发超时)
        tn.read_until(b"Username:", timeout=1)
        tn.write(b"admin\n")
        return "连接成功"
    except socket.timeout:
        return "超时:连接或读取数据失败,请检查网络或增加超时时间"
    finally:
        tn.close()

# 测试(假设目标设备响应缓慢或网络不稳定)
result = telnet_connect_with_timeout("192.168.1.1", timeout=1)
print(result)  # 输出: "超时:连接或读取数据失败,请检查网络或增加超时时间"
处理方案
  • 增加超时时间(如 timeout=10)。

  • 添加重试逻辑:

    python 复制代码
    retries = 3
    for i in range(retries):
        try:
            tn.open(host, port, timeout=5)
            break
        except socket.timeout:
            if i == retries - 1:
                raise

2. ConnectionRefusedError 异常

触发场景
  • 目标设备的 Telnet 服务未启动,或防火墙阻止了连接。
示例代码
python 复制代码
import telnetlib

def telnet_connect_check_port(host, port=2323):  # 故意使用错误端口
    try:
        tn = telnetlib.Telnet(host, port)
        tn.close()
        return "连接成功"
    except ConnectionRefusedError:
        return f"连接被拒绝:端口 {port} 未开放 Telnet 服务"
    except Exception as e:
        return f"其他错误: {str(e)}"

# 测试(假设目标设备未开启 Telnet 或端口错误)
result = telnet_connect_check_port("192.168.1.1", port=2323)
print(result)  # 输出: "连接被拒绝:端口 2323 未开放 Telnet 服务"
处理方案
  • 检查目标设备是否启用 Telnet 服务。

  • 验证端口是否正确(默认 Telnet 端口为 23):

    python 复制代码
    tn = telnetlib.Telnet("192.168.1.1", port=23)  # 使用正确端口
  • 检查防火墙或网络策略是否阻止连接。


3. UnicodeDecodeError 异常

触发场景
  • 设备返回的字节流编码与解码时指定的编码不一致(如设备使用 GBK,但用 UTF-8 解码)。
示例代码
python 复制代码
def decode_response(raw_bytes, encoding="utf-8"):
    try:
        # 尝试用错误编码解码(如设备实际使用 GBK)
        return raw_bytes.decode(encoding)
    except UnicodeDecodeError as e:
        # 记录错误并尝试容错解码
        print(f"解码失败: {e}")
        return raw_bytes.decode(encoding, errors="replace")  # 替换非法字符为 �

# 模拟设备返回 GBK 编码的中文字节流
device_response = "你好".encode("gbk")  # b'\xc4\xe3\xba\xc3'

# 错误解码(用 UTF-8 解码 GBK 字节流)
decoded_text = decode_response(device_response, encoding="utf-8")
print(decoded_text)  # 输出替换后的乱码(如 "���")
处理方案
  1. 统一编码 :确保设备与脚本使用相同编码(如 GBK):

    python 复制代码
    decoded_text = device_response.decode("gbk")  # 正确解码为 "你好"
  2. 自动检测编码 (需安装 chardet 库):

    python 复制代码
    import chardet
    
    detected_encoding = chardet.detect(device_response)["encoding"]
    decoded_text = device_response.decode(detected_encoding)
  3. 容错处理

    python 复制代码
    # 忽略非法字节
    decoded_text = raw_bytes.decode("utf-8", errors="ignore")
    
    # 替换非法字节为占位符
    decoded_text = raw_bytes.decode("utf-8", errors="replace")

总结

异常类型 触发原因 解决方案
socket.timeout 网络或设备响应超时 增加超时时间、添加重试逻辑
ConnectionRefusedError Telnet 服务未启动或端口错误 检查服务状态、验证端口和防火墙设置
UnicodeDecodeError 编码不一致或非法字节 统一编码、自动检测编码、容错解码

通过捕获并处理这些异常,可以显著提升 Telnet 自动化脚本的健壮性和容错能力。

相关推荐
悠悠小茉莉19 分钟前
Win11 安装 Visual Studio(保姆教程 - 更新至2025.07)
c++·ide·vscode·python·visualstudio·visual studio
m0_6256865534 分钟前
day53
python
Real_man1 小时前
告别 requirements.txt,拥抱 pyproject.toml和uv的现代Python工作流
python
站大爷IP2 小时前
Python文件操作的"保险箱":with语句深度实战指南
python
运器1232 小时前
【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
开发语言·人工智能·python·算法·ai·散列表·ai编程
巴里巴气4 小时前
selenium基础知识 和 模拟登录selenium版本
爬虫·python·selenium·爬虫模拟登录
19894 小时前
【零基础学AI】第26讲:循环神经网络(RNN)与LSTM - 文本生成
人工智能·python·rnn·神经网络·机器学习·tensorflow·lstm
JavaEdge在掘金4 小时前
Redis 数据倾斜?别慌!从成因到解决方案,一文帮你搞定
python
ansurfen4 小时前
我的第一个AI项目:从零搭建RAG知识库的踩坑之旅
python·llm
前端付豪4 小时前
20、用 Python + API 打造终端天气预报工具(支持城市查询、天气图标、美化输出🧊
后端·python