首页 > 其他分享 >交换机相关最终_续2

交换机相关最终_续2

时间:2024-10-10 10:48:41浏览次数:6  
标签:network area ip 最终 print 交换机 interface 相关 config

节后修改版2:

import telnetlib
import time

import pandas as pd
import re
def telnet_login(host_ip,username,password):
    tn=telnetlib.Telnet()
    try:
        tn.open(host_ip,port=23,timeout=5)
        tn.read_until(b'Username:',timeout=5)
        tn.write(username.encode('ascii')+b'\n')
        tn.read_until(b'Password:',timeout=5)
        tn.write(password.encode('ascii')+b'\n')
        time.sleep(1)

        command_result=tn.read_until(b'#',timeout=5)
        if b'#' in command_result:
            print(f'{host_ip} telnet success')
        else:
            print(f'{host_ip} telnet failed')
        return tn
    except:
        print(f'{host_ip} telnet failed')
def get_intface_state(tn,host_ip):
    command="show ip interface brief"
    cmd=bytes(command,encoding='ascii')#注意不能写成encodings='ascii'
    tn.write(cmd+b'\n')
    time.sleep(1)
    resultlist=[]
    while True:
        command_result=tn.read_very_eager().decode('ascii')
        #print(command_result)
        #注意不能写成tn.read_very_eager('ascii')
        resultlist.append(command_result)#不能写成resultlist=resultlist.append(command_result)
        if re.findall(r'#',command_result.strip()):
            break
        elif re.findall(r'--More--',command_result.strip()):
            tn.write(b" ")
        else:
            time.sleep(0.05)
            continue
    resultstr="\n".join(resultlist)
    liststr=resultstr.split('\n')
    pd_output=pd.DataFrame()
    listtemp=[]
    for j in liststr:
        if len(re.findall(r'Interface\s+.+',j))>0:
            new_columns=re.split(r'\s+',j.strip())
        if len(re.findall(r'.+\d+\.\d+\.\d+\.\d+\s+.+',j))>0:
            list_find_str=re.split(r'\s+',j.strip())
            listtemp.append(list_find_str)
    #print(listtemp)
    pd_output=pd.DataFrame(listtemp)
    pd_output.columns=new_columns
    print(pd_output)
    pd_output.to_csv(f'{host_ip}.csv')
    return pd_output


def get_ospf_config(tn):
    try:
        tn.write(b"show running-config ospfv2"+b"\n")
        time.sleep(1)
        result_list = []
        command_result = tn.read_very_eager().decode('ascii')
        result_list.append(command_result.strip())
        result_str="\n".join(result_list)
        result_list = result_str.split('\n')
        #print(result_str)
        pd_output=pd.DataFrame()
        import_list = []
        data = []
        data_c = []
        last_area=[]
        df_import = pd.DataFrame()
        count = 0
        #row = None
        for i in result_list:

            match_area = re.match(r'^\s*area\s+(\d\.\d\.\d\.\d)$', i.strip())
            match_interface = re.match(r'^\s*interface\s+(\w+.+)$', i.strip())
            match_network = re.match(r'^\s*network\s+(\w+.+)$', i.strip())
            match_redistribute = re.match(r'^\s*redistribute\s+(\w+)$', i.strip())
            #match_end=re.match(r'^\s*$\s*', i.strip())

            if match_area :
                data.append({'area': match_area.group(1)})
                last_area = match_area.group(1)
                count = 0
            elif match_interface and count < 2:
                if len(data) > 0 and 'interface' not in data[-1].keys():
                    data[-1]['interface'] = match_interface.group(1)
                    count = 0
                elif len(data) > 0 and 'interface'  in data[-1].keys():
                    entry = {'area': last_area}
                    entry['interface']= match_interface.group(1)
                    data.append(entry)
                    count = 0
                else:
                    data.append({'interface': match_interface.group(1)})

                    count = 0
                    #continue
            elif match_network and count < 2:
                 data[-1]['network'] = match_network.group(1)
                 count = 0
            elif match_redistribute:
                findstr = match_redistribute.group(1)
                import_list.append(findstr)
                count = 0
            else:
                count += 1

        if len(import_list) > 0:
            df_import = pd.DataFrame(import_list)
        else:
            df_import.loc[0, 0] = ''
        df_import.columns = ['import']
        #print(data)
        df_area = pd.DataFrame(data)
        # if 'area' not in df_area.columns:
        #     df_area['area']=''
        # if 'interface' not in df_area.columns:
        #     df_area['interface']=''
        # if 'network' not in df_area.columns:
        #     df_area['network']=''
        df = pd.concat([df_area, df_import], axis=1)
        #df['host_ip'] = host_ip
        print(df)
        return df
    except:
        print('error')

def get_ospf_state(tn):
    tn.write(b"show ip ospf neighbor detail"+b'\n')
    time.sleep(1)
    result_list = []
    command_result = tn.read_very_eager().decode('ascii')
    result_list.append(command_result.strip())
    result_str = "\n".join(result_list)
    if re.findall(r'State\s+FULL',result_str):
        return True
    else:
        return False

def ping_test(tn,dest_ip,source_ip):
    command = f"ping {dest_ip} source {source_ip}"
    command = bytes(command, encoding='utf-8')
    tn.write(command + b'\n')
    time.sleep(10)
    ping_result = tn.read_very_eager().decode('ascii')
    # 检查ping测试是否成功
    print(ping_result)
    return "Success rate is 100 percent" in ping_result

def compare_ospf_config(tn1,tn2,df1,df2,interface):
   
    if get_ospf_state(tn1)==True:
        if 'connected' not in df1['import'].values[0]:
            print('router1 has not configuered:import connected')
            modify_ospf_import(tn1)
        if 'connected' not in df2['import'].values[0]:
            print('router2 has not configuered:import connected')
            modify_ospf_import(tn2)
    else:
        if 'area' not in df1.columns:
            if 'interface' in df2.columns:
                if interface in df2['interface'].values:
                    area_config = df2[df2['interface'] == interface]['area'].values[0]
                    if 'network' in df2.columns:
                        network_config = df2[df2['interface'] == interface]['network'].values[0]
                        print(
                            f'router1 configuredarea:{area_config},interface:{interface},network:{network_config}')
                    else:
                        print(f'router 1 configured:{area_config},two router network:network p2p')
                else:
                    area_config = '0.0.0.0'
                    network_config = 'network p2p'
                    print(f'configured two router {area_config},{interface},{network_config}')
        else:
            if 'interface' in df1.columns:
                if interface in df1['interface'].values:
                    if 'interface' in df2.columns:
                        if interface in df2['interface'].values:

                            if df1[df1['interface'] == interface]['area'].values[0] == \
                                    df2[df2['interface'] == interface]['area'].values[0]:
                                if 'network' not in df1.columns:
                                    if 'network' in df2.columns:
                                        network_config = df2[df2['interface'] == interface]['network'].values[0]
                                        print(f'router1 configured:{network_config}')
                                    else:
                                        print('two router configured:network p2p')
                                else:
                                    if 'network' in df2.columns:
                                        if df1[df1['interface'] == interface]['network'].values[0] != \
                                                df2[df2['interface'] == interface]['network'].values[0]:
                                            network_config = df1[df1['interface'] == interface]['network'].values[0]
                                            print(f'router2 configured:{network_config}')
                                    else:
                                        network_config = df1[df1['interface'] == interface]['network'].values[0]
                                        print(f'router2 configured:{network_config}')
                            else:
                                if 'network' in df1.columns:
                                    area_config = df1[df1['interface'] == interface]['area'].values[0]
                                    network_config = df1[df1['interface'] == interface]['network'].values[0]
                                    print(
                                        f'router2 delete the interface adn configured_area:{area_config},{interface},configured_network:{network_config}')
                                else:
                                    area_config = df1[df1['interface'] == interface]['area'].values[0]
                                    print(f'router1 configured:network p2p')
                                    print(
                                        f'router2 configured_area:{area_config},{interface},configured_network:network p2p')
                        else:
                            if 'network' in df1.columns:
                                configured_area = df1[df1['interface'] == interface]['area'].values[0]
                                configured_network = df1[df1['interface'] == interface]['network'].values[0]
                                print(
                                    f'router2 configured_area:{configured_area},{interface},configured_network:network p2p')
                            else:
                                configured_area = df1[df1['interface'] == interface]['area'].values[0]
                                print(
                                    f'router2 configured_area:{configured_area},{interface},configured_network:network p2p')
                                print(f'router1 configured:network p2p')
                    else:
                        if 'network' in df1.columns:
                            area_config = df1[df1['interface'] == interface]['area'].values[0]
                            network_config = df1[df1['interface'] == interface]['network'].values[0]
                            print(
                                f'router2 configured_area:{area_config},{interface},configured_network:{network_config}')
                        else:
                            area_config = df1[df1['interface'] == interface]['area'].values[0]
                            print(
                                f'router2 configured_area:{area_config},{interface},configured_network:network p2p')
                            print(f'router1 configured:network p2p')
                else:
                    if 'interface' in df2.columns:
                        if interface in df2['interface'].values:
                            area_config = df2[df2['interface'] == interface]['area'].values[0]
                            if 'network' in df2.columns:
                                network_config = df2[df2['interface'] == interface]['network'].values[0]
                                print(
                                    f'router1 configured_area:{area_config}, interface, configured_network:{network_config}')
                            else:
                                network_config = 'network p2p'
                                print(
                                    f'router1 configured_area:{area_config}, interface, configured_network:{network_config}')
                                print(f'router2  configured_network:network p2p')
                        else:
                            area_config = '0.0.0.0'
                            network_config = 'network p2p'
                            print(f'configured two router {area_config},{interface},{network_config}')

            else:
                if 'interface' in df2.columns:
                    if interface in df2['interface'].values:
                        area_config = df2[df2['interface'] == interface]['area'].values[0]
                        if 'network' in df2.columns:
                            network_config = df2[df2['interface'] == interface]['network'].values[0]
                            print(f'router1 configured_area:{area_config},{interface},network:{network_config}')
                        else:
                            print(f'router 1 configured_area:{area_config},two router network:network p2p')
                    else:
                        area_config = '0.0.0.0'
                        network_config = 'network p2p'
                        print(f'configured two router {area_config},{interface},{network_config}')


def modify_interface_state(tn,interface):
    commands=[
              "enable",
              "configure terminal",
              f"interface {interface}",
              "no shutdown",
              "exit",
              "exit"
             ]
    for cmd in commands:
        command = bytes(cmd, encoding='utf-8')
        tn.write(command + b'\n')
        time.sleep(2)  # 等待命令执行
def modify_interface_ip(tn,interface,ip,mask):
    commands = [
        "enable",
        "configure terminal",
        f"interface {interface}",
        f"ip address {ip}/{mask}",
        "exit",
        "exit"
    ]
    for cmd in commands:
        command = bytes(cmd, encoding='utf-8')
        tn.write(command + b'\n')
        time.sleep(2)

def modify_ospf_import(tn):
    commands = [
        "enable",
        "configure terminal",
        "router ospf 1",
        "redistribute connected",
        "exit",
        "exit"
    ]
    for cmd in commands:
        command = bytes(cmd, encoding='utf-8')
        tn.write(command + b'\n')
        time.sleep(2)


if __name__=='__main__':
    hosts_ip=['192.168.8.1','192.168.2.2']
    interfaces=['xgei-0/1/1/49','loopback1']
    planed_ip=['10.0.0.2','2.2.2.2','10.0.0.1','3.3.3.3']
    mask=['255.255.255.252','255.255.255.255','255.255.255.252','255.255.255.255']
    mask_config=['30','32','30','32']
    dest_ip=['3.3.3.3','2.2.2.2']
    source_ip=['2.2.2.2','3.3.3.3']

    username='zte'
    password='zte'
    df=pd.DataFrame()#注意不能写成df=DataFrame()
    df1=pd.DataFrame()
    df2=pd.DataFrame()
    #tn=telnet_login(host_ip=hosts_ip[0],username=username,password=password)
    df_ospf_two = pd.DataFrame()
    a=0
    for host_ip in hosts_ip:
        tn=telnet_login(host_ip,username,password)
        if tn:
             df=get_intface_state(tn,host_ip)
             for interface in interfaces:

                 if interface in df['Interface'].values:
                     if df[df['Interface']==interface]['Admin'].values[0]=='down':
                         print(f'{interface} is admin down, please no shutdown it')
                         modify_interface_state(tn, interface)
                     elif df[df['Interface']==interface]['IP-Address'].values[0]!=planed_ip[a] or df[df['Interface']==interface]['Mask'].values[0]!=mask[a]:
                         print(f'{interface} ip address is not {planed_ip[a]} {mask[a]}')
                         modify_interface_ip(tn, interface, planed_ip[a], mask_config[a])
                     else:
                         print(f'{interface } configured is  ok')
                 else:
                     print(f'{interface} has not configuered ip address')
                 a=a+1
             tn.close()
        else:
             print('telnet failed')
    tn1 = telnet_login(hosts_ip[0], username, password)
    tn2 = telnet_login(hosts_ip[1], username, password)

    df1 = get_ospf_config(tn1)
    df2 = get_ospf_config(tn2)
    interface=interfaces[0]
    compare_ospf_config(tn1,tn2,df1, df2, interface)
    ping_test(tn1,dest_ip[0],source_ip[0])

 

标签:network,area,ip,最终,print,交换机,interface,相关,config
From: https://www.cnblogs.com/tjrk/p/18455872

相关文章

  • 43 C 程序动态内存分配:内存区域划分、void 指针、内存分配相关函数(malloc、calloc、re
    目录1 C程序内存区域划分1.1代码区(CodeSection)1.2全局/静态区(Global/StaticSection)1.3栈区(StackSection)1.4 堆区(HeapSection)1.5动态内存分配2void指针(无类型指针)2.1void指针介绍2.2void指针的作用2.3void指针的特点2.4 void指针类......
  • 响应速度相关知识
    在讨论Android性能问题的时候,卡顿、响应速度、ANR这三个性能相关的知识点通常会放到一起来讲,因为引起卡顿、响应慢、ANR的原因类似,只不过根据重要程度,被人为分成了卡顿、响应慢、ANR三种,所以我们可以定义广义上的卡顿,包含了卡顿、响应慢和ANR三种,所以如果用户反馈说手机......
  • 交换机相关最终_续
    1.包含比较检查和修改步骤importparamikoimportosimporttimeimportrandomimportdatetimeimportpandasaspdimportreimportnumpyasnpfromsqlalchemyimporttext,create_engineimportpsycopg2frompsycopg2importsqlfromsqlalchemy.ormimportsessi......
  • 使用python对交换机进行排障自动化运维(锐捷)
    importglobimporttelnetlibimportrefromdatetimeimportdatetimefromtimeimportsleepimportpandasaspdimportosimporttimefrommatplotlibimportpyplotasplt#Telnet连接函数defconnect_telnet(hostname,username,password):  try:  ......
  • 交换机相关最终
    用判断语句实现所有可能场景`importtelnetlibimporttimeimportpandasaspdimportredeftelnet_login(host_ip,username,password):tn=telnetlib.Telnet()try:tn.open(host_ip,port=23,timeout=5)tn.read_until(b'Username:',timeout=5)tn.write(username.encode......
  • 虚拟存储器的相关知识
    题目考查的是虚拟存储器的相关知识。虚拟存储器的概念虚拟存储器是一种内存管理技术,它允许计算机使用比物理内存(RAM)更多的内存。通过将部分内存内容暂时存储在硬盘上,操作系统可以为运行的程序提供比实际物理内存更大的地址空间。局部性原理局部性原理是指程序在执行过程中,对内......
  • 连通性相关
    一些概念连通:无向图中的任意两点都可以互相到达。强连通:有向图中的任意两点都可以互相到达。连通分量:无向图的极大连通子图。强连通分量:有向图的极大强连通子图。DFS生成树:对一张图进行深度优先遍历得到的生成树。树边:在DFS生成树上的边。前向边:由子树的根连向子树内的......
  • RAG系统评测实践详细版:Coze及相关产品评测对比,以及下一代RAG技术
    AIRAG系统评测实践:Coze及相关产品评测对比RAG(检索增强生成)是一种AI框架,它将传统信息检索系统(例如数据库)的优势与生成式大语言模型(LLM)的功能结合在一起,通过将这些额外的知识与自己的语言技能相结合,AI可以撰写更准确、更具时效性且更贴合您的具体需求的文字。RAG通过几个......
  • Linux下操作Nginx相关命令
    1、查看Nginx进程ps-aux|grepnginx圈出的就是Nginx的二进制文件2、测试Nginx配置文件/usr/sbin/nginx-t可以看到nginx配置文件位置3、nginx的使用(启动、重启、关闭)首先利用配置文件启动nginx。nginx-c/usr/local/nginx/conf/nginx.conf重启服务:servicenginxrestar......
  • 在Windows 10中,您可以使用以下命令来转换系统版本(例如,从家庭版升级到专业版)。主要使用
    在Windows10中,您可以使用以下命令来转换系统版本(例如,从家庭版升级到专业版)。主要使用的是slmgr和DISM工具。以下是相关命令:1. 查看当前版本和激活状态bashCopyCodeslmgr/dli2. 输入新产品密钥bashCopyCodeslmgr/ipk<新产品密钥>请将<新产品密钥>替换为您要升......