Python3中telnetlib模块连接网络设备及字节处理详解
本文介绍Python3中telnetlib模块连接网络设备时常见的字节与字符编码不匹配问题。通过解析登录交互过程,展示如何正确处理二进制数据读写,并提供了包含变量替换、结果解码及异常处理的完整脚本示例,帮助开发者实现稳定的设备连接与指令执行。
telnetlib模块基础与编码问题
Python标准库中内置了telnetlib模块,专门用于实现基于Telnet协议的通信功能。
在Python3环境下使用telnetlib连接网络设备时,开发者常会遭遇字节流与字符串之间的编码不匹配问题。
具体的错误提示信息如下所示:
基础连接代码示例
import telnetlib
Host = "10.10.10.10"
# 连接Telnet服务器
tn = telnetlib.Telnet(Host, port=23, timeout=10)
tn.set_debuglevel(0)
# 输入登录用户名
tn.read_until(b'login: ')
tn.write(b"admin" + b'\n')
# 输入登录密码
tn.read_until(b'Password: ')
tn.write(b"Admin@1234" + b'\n')
tn.read_until(b'#')
tn.write(b"cd /home/sd" + b'\n')
tn.read_until(b'#')
tn.write(b"ls -al" + b'\n')
r = tn.read_until(b'#').decode('ASCII')
r1 = r.split(r"\r\n")
for i in r1:
print(i)
tn.close()
以下为一个典型的网络设备交互实例。
交互式连接调试过程
>>> tn=telnetlib.Telnet("10.10.0.6",timeout=2)
>>> tn.read_until(b'login: ',timeout=2)
b"\r\n******************************************************************
****\r\n* Copyright (c) 2004-2018 New H3C Technologies Co., Ltd. All rig
rved.*\r\n* Without the owner's prior written consent,
*\r\n* no decompiling or reverse-engineering shall be allowed.
*\r\n**********************************************************
************\r\n\r\nlogin: "
>>> tn.write(b'admin'+b'\n')
>>> tn.read_until(b'Password: ',timeout=2)
b'jgtl\r\r\nPassword: '
>>> tn.write(b'Admin@123'+b'\n')
>>> tn.read_until(b'>')
b'\r\n<bangong-01>'
>>> tn.write(b'ping 10.10.0.7')
>>> tn.read_until(b'>')
上述过程展示了命令行手动执行的结果。若将其转化为自动化脚本,主要需解决两个核心问题:一是如何对替换变量进行正确的编码与解码处理,二是对设备返回的输出结果进行解码操作。
完整自动化脚本实现
#-*- coding:utf-8 -*-
import telnetlib
import re
import csv
import sys
import time
from datetime import datetime
host_dict={
"ip":"10.10.0.6",
"user":"admin",
"pwd":"Admin@123"
}
def get_loss(addrlist):
host=host_dict["ip"]
user=host_dict["user"]
pwd=host_dict["pwd"]
print (host)
resultlist = []
#try:
tn = telnetlib.Telnet(host, timeout=2)
print ("AA")
if len(host_dict["pwd"]) and len(host_dict["user"]):
print ("BB")
tn.read_until(b"login: ", timeout=3)
#tn.write(b"admin"+b"\n")
tn.write(user.encode()+b"\n")
tn.read_until(b"Password: ", timeout=3)
#tn.write(b"Admin@123"+b"\n")
tn.write(pwd.encode()+ b"\n")
# p_error = re.compile("found at")
if tn.read_until(b">", timeout=4).find(b">") != -1:
print("Connect to {host} ...... ".format(host=host))
tn.write(b"ping 127.0.0.1\n")
print (tn.read_until(b'01>'))
else:
print("%s Wrong username or password!!!" % host)
return ""
#tn.read_until(b">")
if len(addrlist) != 0:
for i in range(len(addrlist)-1):
tep = {}
command = "ping " + addrlist[i]
print("command:", command)
tn.write(command.encode() + b"\n")
result = str(tn.read_until(b"01>"))
print(result)
re_loss = re.compile("\d+\.\d+%")
loss = re_loss.findall(result)
tep[host] = loss[0]
resultlist.append(tep)
#if p_error.search(result.decode()):
# print("There is a error in this command: {0}".format(c.decode()))
tn.close()
#except Exception as e:
#if e:
# print ("Connect to {host} Failed!!!".format(host=host),e)
#return ""
return resultlist
if __name__=="__main__":
addrlist=['10.10.0.2','10.10.0.5']
print ("get_loss",get_loss(addrlist))
以上内容为本文的全部分享,希望能为读者的学习提供有益参考,同时也欢迎大家继续支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









