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

相关推荐
郭庆汝26 分钟前
pytorch、torchvision与python版本对应关系
人工智能·pytorch·python
思则变3 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
漫谈网络4 小时前
WebSocket 在前后端的完整使用流程
javascript·python·websocket
try2find5 小时前
安装llama-cpp-python踩坑记
开发语言·python·llama
博观而约取6 小时前
Django ORM 1. 创建模型(Model)
数据库·python·django
精灵vector8 小时前
构建专家级SQL Agent交互
python·aigc·ai编程
Zonda要好好学习8 小时前
Python入门Day2
开发语言·python
Vertira8 小时前
pdf 合并 python实现(已解决)
前端·python·pdf
太凉8 小时前
Python之 sorted() 函数的基本语法
python
项目題供诗8 小时前
黑马python(二十四)
开发语言·python