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

telnet操作中兴设备

时间:2024-10-11 13:21:51浏览次数:1  
标签:username telnet 中兴 host 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,telnet,中兴,host,interface,password,port,match,设备
From: https://www.cnblogs.com/norvell/p/18458169

相关文章

  • 简便安装,零要求高度,一体化设计!SD202型拉线地表位移监测设备
    简便安装,零要求高度,一体化设计!SD202型拉线地表位移监测设备SD202型拉线地表位移是一种具有一体化密封设计的监测设备。其外观线条流畅美观,安装简便,无需打开机壳,对安装高度没有任何要求。该设备具备无线收发能力,并内置电池和SIM卡,无需额外连接采发模块。因此,它适用于测点较为分散、......
  • telnetlib操作中兴设备
    importtelnetlib,re,os,threading,multiprocessing,datetimeimportpandasaspdfrompandaspd.set_option('display.width',None)#pd.options.display.max_columns=None#pd.options.display.max_rows=Nonepath=os.getcwd()deftelnet(host,port,......
  • 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          ......
  • 福建联通吉比特H80g进telnet获取超级密码改桥接
    本人博客原文链接:福建联通吉比特H80g进telnet获取超级密码改桥接最近福建联通宽带换了一个光猫,型号是吉比特H80G,自己尝试了获取管理员密码,大致流程是:1、记录自己的loid、宽带帐号、密码等配置信息;2、长按光猫reset键回复出场设置,此时管理员账户和密码是CUAdminCUAdmin,在高级......
  • 手把手教你学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)
    ......