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

交换机相关最终_续3

时间:2024-10-11 11:00:40浏览次数:1  
标签:area ip 最终 tn 交换机 command interface 相关 config

包含修改版:

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 = []
        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']='null'
        if 'interface' not in df_area.columns:
            df_area['interface']='null'
        if 'network' not in df_area.columns:
            df_area['network']='null'
        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):
        print('The ospf state is FULL!')
        return True
    else:
        print('The ospf state is not FULL!')
        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 modidy_ospf_config(tn,area,interface,network):
    command=[
        "enable",
        "configure terminal",
        "router ospf 1",
        f"area {area}",
        f"interface {interface}",
        f"network {network}",
        "exit",
        "exit",
        "exit",
        "exit",
    ]
    for cmd in command:
        command = bytes(cmd, encoding='utf-8')
        tn.write(command + b'\n')
        time.sleep(0.1)
    time.sleep(20)
def remove_ospf_config(tn,area):
    command=[
        "enable",
        "configure terminal",
        "router ospf 1",
        f"no area {area}",
        "exit",
        "exit",
    ]
    for cmd in command:
        command = bytes(cmd, encoding='utf-8')
        tn.write(command + b'\n')
        time.sleep(0.1)
def compare_ospf_config(tn1, tn2, df1, df2, interface):

        network_config = 'point-to-point'
        if interface in df1['interface'].values:
            if interface in df2['interface'].values:
                if df1[df1['interface']==interface]['area'].values[0]==df2[df2['interface']==interface]['area'].values[0]:
                    if df1[df1['interface']==interface]['network'].values[0]==df2[df2['interface']==interface]['network'].values[0]:
                       print("two router area configured are ok !")
                    else:
                         area_config = df1[df1['interface'] == interface]['area'].values[0]
                         modidy_ospf_config(tn1,area_config,interface,network_config)
                         modidy_ospf_config(tn2, area_config, interface, network_config)
                else:
                    area_config=df1[df1['interface']==interface]['area'].values[0]
                    area_remove=df2[df2['interface']==interface]['area'].values[0]
                    print('configured areas are not same,trying modify it')
                    remove_ospf_config(tn2,area_remove)
                    modidy_ospf_config(tn1, area_config, interface, network_config)
                    modidy_ospf_config(tn2, area_config, interface, network_config)

            else:
                area_config = df1[df1['interface'] == interface]['area'].values[0]
                print(f'router2 has not configured the interface {interface},trying modify it')
                modidy_ospf_config(tn1, area_config, interface, network_config)
                modidy_ospf_config(tn2, area_config, interface, network_config)
        else:
            if interface in df2['interface'].values:
                print(f'router1 has not configured the interface {interface},router2 configured,trying modify it')
                area_config=df2[df2['interface']==interface]['area'].values[0]
                modidy_ospf_config(tn1, area_config, interface, network_config)
                modidy_ospf_config(tn2, area_config, interface, network_config)

            else:
                print(f'two routers have not configured the interface {interface},trying modify them')
                area_config='0.0.0.0'
                modidy_ospf_config(tn1, area_config, interface, network_config)
                modidy_ospf_config(tn2, area_config, interface, network_config)

        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)
        get_ospf_state(tn1)

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(0.1)


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])

 

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

相关文章

  • 第七章 RabbitMQ之交换机
    目录一、介绍二、Fanout Exchange2.1.案例演示 2.1.1.创建SpringBoot工程2.1.2.父工程pom依赖2.1.3.生产者pom依赖  2.1.4.生产者配置文件2.1.5. 生产者核心代码 2.1.6.消费者RabbitMQConfig 2.1.7.消费者pom依赖2.1.8.消费者配置文件2.1.9. 消费......
  • 信号相关
    信号信号是软件中断,提供了一种处理异步事件的方法,如在终端按下Ctrl+C会产生SIGINT中断信号。信号产生用户键入:必须在终端按下Ctrl+C和Ctrl+X等会产生对应信号硬件异常产生信号:除数为0、无效的内存引用等,如对执行一个无效内存引用的进程产生SIGSEGV信号进程调用kill函数将信......
  • 谈JVM xmx, xms等内存相关参数合理性设置
    作者:京东零售刘乐上一篇文章说到JVM垃圾回收算法的两个优化标的:吞吐量和停顿时长,并提到这两个优化目标是有冲突的。那么有没有可能提高吞吐量而不影响停顿时长,甚至缩短停顿时长呢?答案是有可能的,提高内存占用(MemoryFootprint)就有可能同时优化这两个标的,这篇文章就来聊聊内存相关......
  • 51c嵌入式分享~三极管相关1
    一、PNP与NPN两种三极管使用方法  分享这篇文章总结下关于NPN和PNP两种型号三极管的使用和连接方法。    在单片机应用电路中三极管主要的作用就是开关作用。PNP与NPN两种三极管使用方法    上图中,横向左侧的引脚叫做基极b,有一个箭头的是发射极e,剩下的一个引脚就是集电......
  • arm imx6ull docker启动失败问题查找与解决 内核配置相关
    1、增加POSIXMessageqeue:couldnotgetinitialnamespace:nosuchfileordirectory CONFIG_POSIX_MQUEUE=y2、增加namespacefailedtosettoinitialnamespaceCONFIG_NAMESPACES=y3、创建网络失败,veth配置:dockercreateendpointquirky_shternonnetworkbridge......
  • 交换机相关最终_续2
    节后修改版2: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)......
  • 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:  ......