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 自动化脚本的健壮性和容错能力。

相关推荐
简简单单做算法9 分钟前
基于mediapipe深度学习的虚拟画板系统python源码
人工智能·python·深度学习·mediapipe·虚拟画板
愿望会实现吧2 小时前
|从零开始的Pyside2界面编程|绘图、布局及页面切换
python
zstar-_2 小时前
【Ragflow】24.Ragflow-plus开发日志:增加分词逻辑,修复关键词检索失效问题
人工智能·python·llm
love530love2 小时前
【笔记】2025 年 Windows 系统下 abu 量化交易库部署与适配指南
大数据·运维·人工智能·windows·笔记·python·conda
love530love2 小时前
【笔记】为 Python 项目安装图像处理与科学计算依赖(MINGW64 环境)
开发语言·图像处理·人工智能·windows·笔记·python·numpy
奉系坤阀2 小时前
Ubuntu终端性能监视工具
linux·运维·服务器·python·ubuntu
YYXZZ。。2 小时前
PyTorch-Transforms的使用(二)
人工智能·pytorch·python
lczdyx2 小时前
一键净化Excel数据:高性能Python脚本实现多核并行清理
python·excel·pandas·数据清洗·数据处理·自动化办公·openpyxl
Tom Boom3 小时前
40. 自动化异步测试开发之编写异步业务函数、测试函数和测试类(类写法)
运维·自动化测试·python·selenium·自动化·自动化测试框架·异步编程
Ronin-Lotus3 小时前
深度学习篇---OC-SORT简介
人工智能·python·深度学习·oc-srot