交换机相关最终_续2

节后修改版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])

 

posted @ 2024-10-10 10:53  tangi  阅读(4)  评论(0编辑  收藏  举报