首页 > 其他分享 >telnetlib操作中兴设备

telnetlib操作中兴设备

时间:2024-10-10 23:01:47浏览次数:10  
标签:username 中兴 host telnetlib interface password port match 设备

import telnetlib, re, os, threading, multiprocessing, datetime
import pandas as pd
from pandas
pd.set_option('display.width', None)
# pd.options.display.max_columns = None
# pd.options.display.max_rows = None
path = os.getcwd()

def telnet(host, port, username, password):
tn = telnetlib.Telnet(host, port, timeout=5)
tn.read_until(b"Username:")
tn.write(username.encode('ascii') + b"\n")
tn.read_until(b"Password:")
tn.write(password.encode('ascii') + b"\n")
tn.read_until(b"#", timeout=5)
tn.write(b"terminal length 0 \n") #zte
tn.read_until(b"#")
return tn

def runcommands(host, port, username, password, command):
commands = command.split("\n")
output = ""
try:
tn = telnet(host, port, username, password)
for cmd in commands:
tn.write(cmd.encode('ascii') + b"\n")
output_tmp = tn.read_until(b"#", 5)
output += output_tmp.decode('ascii')
tn.close()
print(output)
except Exception as e:
print(f"命令执行失败,{e}")
try:
tn.close()
except Exception as e:
print("tn close failed")
return output

def showInterfaceBrief(host, port, username, password,command="show interface bri"):
output = runcommands(host, port, username, password, command)
outputs = output.splitlines()
msgs = []
for line in outputs:
# 提取详细接口信息
pattern = r'(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(down|up)\s+(down|up)\s+(down|up)\s+(\S*)'
matchs = re.findall(pattern, line)
if matchs != []:
match = matchs[0]
if len(match) == 8:
desc = match[7]
else:
desc = ""
msgs.append({
'interface': match[0],
'portattribute': match[1],
'mode': match[2],
'bw(mbps)': match[3],
'admin_status': match[4],
'phy_status': match[5],
'prot_status': match[6],
'description': desc,
})
df = pd.DataFrame(msgs)
df["host"] = host
print(df)
return df

def showInterfaceDetail(host, port, username, password,command="show interface "):
try:
interfaces = showInterfaceBrief(host, port, username, password, "show interface bri")
interfaces["bw"] = None
interfaces["mtu"] = None
interfaces["In_Bytes"] = None
interfaces["E_Bytes"] = None
tn = telnet(host, port, username, password)
for interface in interfaces["interface"]:
cmd = command + interface
tn.write(cmd.encode('ascii') + b"\n")
output = tn.read_until(b"#", 5).decode("ascii")
pattern = r'BW\s+(\d+)'
match = int(re.findall(pattern, output, re.S)[0])
interfaces.loc[interfaces["interface"] == interface, "bw"] = match
pattern = r'MTU\s+(\d+)'
match = int(re.findall(pattern, output, re.S)[0])
interfaces.loc[interfaces["interface"] == interface, "mtu"] = match
pattern = r'In_Bytes\s+(\S+)\s+'
match = int(re.findall(pattern, output, re.S)[0])
interfaces.loc[interfaces["interface"] == interface, "In_Bytes"] = match
pattern = r'E_Bytes\s+(\S+)\s+'
match = int(re.findall(pattern, output, re.S)[0])
interfaces.loc[interfaces["interface"] == interface, "E_Bytes"] = match
tn.close()
print(interfaces)
except Exception as e:
print(f"命令执行失败,{e}")
try:
tn.close()
except Exception as e:
print("tn close failed")
return interfaces

def showIpInterfacesBrief(host, port, username, password, command="show ip int bri"):
output = runcommands(host, port, username, password, command)
outputs = output.splitlines()
msgs = []
for line in outputs:
# 提取详细接口信息
pattern = r'(\S+)\s+(\S+)\s+(\S+)\s+(down|up)\s+(down|up)\s+(down|up)\s*'
matchs = re.findall(pattern, line)
if matchs != []:
match = matchs[0]
msgs.append({
'interface': match[0],
'ip_address': match[1],
'mask': match[2],
'admin_status': match[3],
'phy_status': match[4],
'prot_status': match[5]
})
df = pd.DataFrame(msgs)
df["host"] = host
print(df)
return df

def pingtest(host, port, username, password, command="ping 192.168.10.1"):
output = runcommands(host, port, username, password, command)
pattern = r'Success rate is (\d+)\s*'
matchs = int(re.findall(pattern, output)[0])
if matchs == 0:
print(f'host {host} {command} is failed')
else:
print(f'host {host} {command} is successed, the success rate is {matchs}')


def showIpOspfNeighbor(host, port, username, password, command="show ip ospf neighbor"):
output = runcommands(host, port, username, password, command)
pattern = r'\((\S+)\)'
routerid = re.search(pattern, output).group(1)
outputs = output.splitlines()
neighbors = []
for line in outputs:
# 提取详细接口信息
pattern = r'(\S+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)'
matchs = re.findall(pattern, line)
if matchs != []:
match = matchs[0]
neighbors.append({
'neighborid': match[0],
'pri': match[1],
'state': match[2],
'deadtime': match[3],
'address': match[4],
'interface': match[5]
})
df = pd.DataFrame(neighbors)
df["routerid"] = routerid
print(df)
return df

def showIpOspfInterfaces(host, port, username, password):
output = runcommands(host, port, username, password, "show ip ospf interface")
outputs = re.split(r'\n\s*\n', output.strip())
ospf_msgs = []
for msg in outputs:
if "xgei" in msg:
# host\interface\status\address\area\networktype\authentication\hello\dead\retransmit
pattern = r'(\S*xgei\S+)\s+is\s(up|down)'
matchs = re.findall(pattern, msg)
interface = matchs[0][0]
status = matchs[0][1]
pattern = r'.*Address\s+(\S+)\s+'
matchs = re.findall(pattern, msg)
address = matchs[0]
pattern = r'.*the\sarea\s(\S+)\s'
matchs = re.search(pattern, msg)
area = matchs[0]
pattern = r'.*Network\sType\s(\S+)'
matchs = re.findall(pattern, msg)
networktype = matchs[0]
pattern = r'.*Authentication\sType\s(\S+)'
matchs = re.findall(pattern, msg)
authentication = matchs[0]
pattern = r'.*Hello\s(\d+),\sDead\s(\d+),\sRetransmit\s(\d+)'
matchs = re.findall(pattern, msg)
hello = matchs[0][0]
dead = matchs[0][1]
retransmit = matchs[0][2]
ospf_msgs.append({
"host": host,
"interface": interface,
"status": status,
"address": address,
"area": area,
"networktype": networktype,
"authentication": authentication,
"hello": hello,
"dead": dead,
"retransmit": retransmit
})
df = pd.DataFrame(ospf_msgs)
print(df)
return df

def checkInterfacesAndRepair(host, port, username, password, interfaces):
print("----------------before repair interface----------------")
interfaces_df = showInterfaceBrief(host, port, username, password)
for interface in interfaces:
# if interface in interfaces_df["interfaces"]:
# print(f"{host} do not have {interface}")
# continue
status = interfaces_df.loc[interfaces_df["interface"] == interface, "admin_status"].values[0]
if status == "down":
runcommands(host, port, username, password, f"conf t\ninterface {interface}\nno shutdown\nexit\nexit\nwrite\n")
print(f"{host} interface {interface} is down, now set it up")
else:
print(f"{host} interface {interface} is not down")
interfaces_after_df = showInterfaceBrief(host, port, username, password)
print("----------------after repair interface----------------")
for interface in interfaces:
status = interfaces_df.loc[interfaces_df["interface"] == interface, "admin_status"].values[0]
if status == "up":
print(f"{host} interface {interface} is up after repaired")
else:
print(f"{host} interface {interface} is still down after repaired")


if __name__ == '__main__':
devices = [{"ip":"129.60.161.169","port":"23","username":"zte","password":"zte"},
{"ip":"129.60.161.170","port":"23","username":"zte","password":"zte"}]
for device in devices:
host = device["ip"]
port = device["port"]
username = device["username"]
password = device["password"]
print(f'{host}-{port}-{username}-{password}')
# # ---------执行命令----------
# output = runcommands(host, port, username, password, "show running-config\nshow interface brief \nshow ip interface brief")
# current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
# filename = "showrun_" + host + "_" + current_time + ".txt"
# with open(filename, "w", encoding="utf-8") as file:
# file.write(output)

# # --------提取show interface brief信息-------
# output = showInterfaceBrief(host, port, username, password)
# current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
# filename = "InterfaceBrief_" + host + "_" + current_time + ".csv"
# output.to_csv(filename)

# # --------提取show ip interface brief信息-------
# output = showIpInterfacesBrief(host, port, username, password)
# current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
# filename = "IPInterfaceBrief_" + host + "_" + current_time + ".csv"
# output.to_csv(filename)

# # --------ping测试------------
# pingtest(host, port, username, password, "ping 192.168.10.1")

# # --------获取端口速率\mtu信息---------
# output = showInterfaceDetail(host, port, username, password)
# current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
# filename = "InterfaceDetail_" + host + "_" + current_time + ".csv"
# output.to_csv(filename)

# # -------获取ospf邻居信息---------
# output = showIpOspfNeighbor(host, port, username, password)

# # --------修复端口------------
# interfaces = ["xgei-0/2/0/8", "xgei-0/2/0/19", "xgei-0/2/0/20"]
# checkInterfacesAndRepair(host, port, username, password, interfaces)

# -------显示ospf端口详细信息--------
showIpOspfInterfaces(host, port, username, password)


# # -------------多线程--------------
# # 创建线程
# threads = []
# for login_msg in login_msgs:
# host = login_msg["ip"]
# port = login_msg["port"]
# threads.append(threading.Thread(showInterfaceDetail(host, port, "huawei", "huawei")))
#
# # 启动线程
# for t in threads:
# t.start()
#
# # 等待所有线程完成
# for t in threads:
# t.join()

# # -------------多进程--------------
# # 创建进程池
# with multiprocessing.Pool(processes=len(login_msgs)) as pool:
# # 向进程池添加任务
# for login_msg in login_msgs:
# host = login_msg["ip"]
# port = login_msg["port"]
# pool.apply_async(showInterfaceDetail(host, port, "huawei", "huawei"))
#
# # 等待所有子进程完成
# pool.close()
# pool.join()

 

标签:username,中兴,host,telnetlib,interface,password,port,match,设备
From: https://www.cnblogs.com/norvell/p/18457388

相关文章

  • ESP32移植Openharmony设备开发---(1)环境搭建
    第一章环境搭建1.下载ubuntu创建虚拟机内存分配建议8G硬盘大于200G                                                                下载ubuntu20.04复制特征码打开迅雷即可下载5F5E8848426......
  • ESP32移植Openharmony设备开发---(3)任务调度
    任务调度官方文档:OpenAtomOpenHarmony基本概念从系统角度看,任务是竞争系统资源的最小运行单元。任务可以使用或等待CPU、使用内存空间等系统资源,各任务的运行相互独立。OpenHarmonyLiteOS-M的任务模块可以给用户提供多个任务,实现任务间的切换,帮助用户管理业务程序流程。......
  • java+vue计算机毕设高校教学设备管理系统【源码+程序+论文+开题】
    本系统(程序+源码)带文档lw万字以上文末可获取一份本项目的java源码和数据库参考。系统程序文件列表开题报告内容研究背景随着高等教育事业的蓬勃发展,高校教学设备作为支撑教学与科研活动的重要物质基础,其管理效率与水平直接影响到教育质量与科研成果。近年来,高校教学设备......
  • 内核编译 设备驱动 驱动程序
    内核编译一、内核编译的步骤编译步骤:(linux内核源码的顶层目录下操作)1.拷贝默认配置到.config       cpconfig_mini2440_td35.config2.makemenuconfig内核配置    makemenuconfig3.makeuImage          ......
  • 手把手教你学PCIE(6.9)--驱动程序开发实例的网络设备驱动程序开发
    目录1.开发环境准备1.1安装开发工具1.2创建项目目录2.驱动程序代码2.1驱动程序头文件2.2驱动程序主文件3.编译驱动程序4.加载和卸载驱动程序5.测试驱动程序6.总结开发一个网络设备驱动程序是一个复杂的任务,涉及到网络协议栈的集成和硬件设备的管理。在......
  • 10 - platform 设备驱动
    ----整理自王利涛老师课程文章目录1.第一个platform驱动2.platform驱动注册过程分析2.1platform总线的注册过程2.2platform设备的注册过程2.3platform驱动的注册过程3.platformbusmatch方法4.注册一个字符设备驱动5.自动创建设备节点6.platform......
  • 基于springboot的设备档案管理系统(含源码+sql+视频导入教程+文档+PPT)
    ......
  • 煤矿项目车载设备又多又复杂?我们建议这样做
    煤矿生产环境复杂多变,存在诸多不确定因素,如高温、低氧、多尘、黑暗等,这些都给煤矿生产带来了极大的安全隐患。传统的煤矿生产管理方式依赖人工巡检,存在效率低下、盲区监控等问题。现在越来越多的煤矿行业开始采用矿车搭配车载设备的方式,实现对井下作业的安全监管。我们近期也遇......
  • 基于nodejs+vue移动互联时代的设备管理系统[开题+源码+程序+论文]计算机毕业设计
    本系统(程序+源码+数据库+调试部署+开发环境)带文档lw万字以上,文末可获取源码系统程序文件列表开题报告内容研究背景随着移动互联网技术的飞速发展,各类智能设备在日常生产和生活中的应用日益广泛。从智能手机到可穿戴设备,从工业控制设备到智能家居系统,这些设备极大地提升了......
  • fmql之Linux设备驱动框架
    设备驱动框架正点原子第39章---LED驱动框架    测试成功:贴代码(不需要测试APP)/***************************************************************Copyright©ALIENTEKCo.,Ltd.1998-2029.Allrightsreserved.文件名:leds-atk.c作者......