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

相关推荐
Cloud Traveler18 分钟前
Java并发编程常见问题与陷阱解析
java·开发语言·python
山海不说话28 分钟前
PyGame游戏开发(含源码+演示视频+开结题报告+设计文档)
python·pygame
Y3174292 小时前
Python Day 22 学习
python·学习
正在走向自律2 小时前
Python 自动化脚本开发秘籍:从入门到实战进阶(6/10)
开发语言·python
白熊1882 小时前
【计算机视觉】基于Python的相机标定项目Camera-Calibration深度解析
python·数码相机·计算机视觉
仙人掌_lz3 小时前
深入理解深度Q网络DQN:基于python从零实现
python·算法·强化学习·dqn·rl
小雅痞3 小时前
[Java][Leetcode middle] 80. 删除有序数组中的重复项 II
java·python·leetcode
大叔_爱编程3 小时前
p020基于Django的4S店客户管理系统
vue.js·python·django·毕业设计·源码·课程设计·4s店客户管理系统
yorushika_4 小时前
python打卡训练营打卡记录day22
开发语言·python·机器学习
代码的乐趣4 小时前
支持selenium的chrome driver更新到136.0.7103.92
chrome·python·selenium