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

交换机相关最终

时间:2024-10-09 11:01:23浏览次数:1  
标签:network area 最终 交换机 command result pd import 相关

  1. 用判断语句实现所有可能场景
    `
    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 = []
df_import = pd.DataFrame()
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())

        if match_area:
            data.append({'area': match_area.group(1)})
        elif match_interface:
             data[-1]['interface'] = match_interface.group(1)
        elif match_network:
             data[-1]['network'] = match_network.group(1)

        if match_redistribute:
            findstr = match_redistribute.group(1)
            import_list.append(findstr)
    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')

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

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 df[df['Interface']==interface]['Admin'].values[0]=='down':
                print(f'{interface} is admin down, please no shutdown it')
             if df[df['Interface']==interface]['IP-Address'].values[0]!=planed_ip[a]:
                 print(f'{interface} ip address is not {planed_ip[a]}')
             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)

if 'area' not in df1.columns:
    if 'interface' in df2.columns:
        if interfaces[0] in df2['interface'].values:
            area_config= df2[df2['interface'] == interfaces[0]]['area'].values[0]
            if 'network' in df2.columns:
                network_config=df2[df2['interface']==interfaces[0]]['network'].values[0]
                print(f'router1 configuredarea:{area_config},interface:{interfaces[0]},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},{interfaces[0]},{network_config}')
else:
    if 'interface' in df1.columns:
        if interfaces[0] in df1['interface'].values:
            if 'interface' in df2.columns:
                if interfaces[0] in df2['interface'].values:

                    if df1[df1['interface'] == interfaces[0]]['area'].values[0] == \
                            df2[df2['interface'] == interfaces[0]]['area'].values[0]:
                        if 'network' not in df1.columns:
                            if 'network' in df2.columns:
                                network_config = df2[df2['interface'] == interfaces[0]]['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'] == interfaces[0]]['network'].values[0] != \
                                        df2[df2['interface'] == interfaces[0]]['network'].values[0]:
                                    network_config = df1[df1['interface'] == interfaces[0]]['network'].values[0]
                                    print(f'router2 configured:{network_config}')
                            else:
                                network_config = df1[df1['interface'] == interfaces[0]]['network'].values[0]
                                print(f'router2 configured:{network_config}')
                    else:
                        if 'network' in df1.columns:
                            area_config = df1[df1['interface'] == interfaces[0]]['area'].values[0]
                            network_config = df1[df1['interface'] == interfaces[0]]['network'].values[0]
                            print(
                                f'router2 delete the interface adn configured_area:{area_config},{interfaces[0]},configured_network:{network_config}')
                        else:
                            area_config = df1[df1['interface'] == interfaces[0]]['area'].values[0]
                            print(f'router1 configured:network p2p')
                            print(
                                f'router2 configured_area:{area_config},{interfaces[0]},configured_network:network p2p')
                else:
                    if 'network' in df1.columns:
                        configured_area = df1[df1['interface'] == interfaces[0]]['area'].values[0]
                        configured_network = df1[df1['interface'] == interfaces[0]]['network'].values[0]
                        print(
                            f'router2 configured_area:{configured_area},{interfaces[0]},configured_network:network p2p')
                    else:
                        configured_area = df1[df1['interface'] == interfaces[0]]['area'].values[0]
                        print(
                            f'router2 configured_area:{configured_area},{interfaces[0]},configured_network:network p2p')
                        print(f'router1 configured:network p2p')
            else:
                if 'network' in df1.columns:
                    area_config = df1[df1['interface'] == interfaces[0]]['area'].values[0]
                    network_config = df1[df1['interface'] == interfaces[0]]['network'].values[0]
                    print(
                        f'router2 configured_area:{area_config},{interfaces[0]},configured_network:{network_config}')
                else:
                    area_config = df1[df1['interface'] == interfaces[0]]['area'].values[0]
                    print(f'router2 configured_area:{area_config},{interfaces[0]},configured_network:network p2p')
                    print(f'router1 configured:network p2p')
        else:
            if 'interface' in df2.columns:
                if interfaces[0] in df2['interface'].values:
                    area_config = df2[df2['interface'] == interfaces[0]]['area'].values[0]
                    if 'network' in df2.columns:
                        network_config = df2[df2['interface'] == interfaces[0]]['network'].values[0]
                        print(
                            f'router1 configured_area:{area_config}, interfaces[0], configured_network:{network_config}')
                    else:
                        network_config = 'network p2p'
                        print(
                            f'router1 configured_area:{area_config}, interfaces[0], 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},{interfaces[0]},{network_config}')

    else:
        if 'interface' in df2.columns:
            if interfaces[0] in df2['interface'].values:
                area_config = df2[df2['interface'] == interfaces[0]]['area'].values[0]
                if 'network' in df2.columns:
                    network_config = df2[df2['interface'] == interfaces[0]]['network'].values[0]
                    print(f'router1 configured_area:{area_config},{interfaces[0]},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},{interfaces[0]},{network_config}')

2.信心采集状态
import paramiko
import os
import time
import random
import datetime
import pandas as pd
import re
import numpy as np
from sqlalchemy import text, create_engine
import psycopg2
from psycopg2 import sql
from sqlalchemy.orm import sessionmaker
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy import create_engine, MetaData, Table, inspect
import schedule

import telnetlib
import threading
import time

def get_info_telnet(host_ip, username, password):

host_ip = '129.60.161.169'
username = 'zte'
password = 'zte'

tn = telnetlib.Telnet()
try:

    tn.open(host_ip, port=23, timeout=5)
    print('%s connected ssuccess !' % host_ip)

    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'#' not in command_result:
        print('%s登录失败' % host_ip)
    else:
        print('%s登录成功' % host_ip)

except:

    print('%s网络连接失败' % host_ip)

command = "show clock"
command = bytes(command, encoding='utf-8')
tn.write(command + b'\r\n')
run_time = tn.read_until(b'#')
run_time = re.findall(r"\d+:\d+:\d+\s+\w+\s+\w+\s+\w+\s+\d+\s+2024", run_time.decode('GB18030'))[0]

command = "show interface brief"
command = bytes(command, encoding='utf-8')
tn.write(command + b'\n')
time.sleep(1)

result_list = []
while (True):
    command_result = tn.read_very_eager().decode('ascii')
    # print(command_result)
    result_list.append(command_result)
    if re.findall(r"--More--", command_result.strip()):
        tn.write(b" ")

    elif re.findall(r"#", command_result.strip()):
        break
    else:
        time.sleep(0.05)
        continue

result_str = "\n".join(result_list)
list_str = result_str.split('\n')

pd_result = pd.DataFrame()
list_temperature_vec = []
for j in list_str:
    regex = re.compile(r'\w+gei.+\s+.+\s+.+\s+.+\s+.+\s+.+\s+.+', re.S)
    # print(regex.findall(j))
    # print(len(regex.findall(j)))
    if len(re.findall(r"Interface", j)) > 0:
        new_columns = list_find_str = re.split(r'\s+', j)
        new_columns = new_columns[0:8]

    if len(regex.findall(j)) > 0:
        list_find_str = regex.findall(j)[0]
        list_find_str = re.split(r'\s+', list_find_str)
        list_temperature_vec.append(list_find_str)
pd_result = pd.DataFrame(list_temperature_vec)
pd_result.columns = new_columns


tn.close()
return pd_result

if name == 'main':

host_ip = '129.60.161.169'
username = 'zte'
password = 'zte'
pd_output = get_info_telnet(host_ip, username, password)

`

3.故障数据分析
`
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
import os

import numpy as np
import math
import random
import threading

from datetime import datetime, timedelta
import pandas as pd
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
from datetime import datetime
import json
import re
import time

import itertools
import warnings
warnings.filterwarnings("ignore")

if name == 'main':
try:
engine = create_engine('postgresql://5ga-cmcc:5ga-cmcc@localhost:5432/postgres')
Session = sessionmaker(bind=engine)
query = """
SELECT * FROM traffic_table where port_name = 'xgei-0/2/0/24' ORDER BY time desc LIMIT 200;
"""
with Session() as session:
result = session.execute(text(query))
data = pd.DataFrame(result.fetchall(), columns=result.keys())
data['time'] = pd.to_datetime(data['time'], format='%Y-%m-%d %H%M%S')
data.sort_values('time', inplace=True)
data.reset_index(level=None, drop=True, inplace=True)
session.close()
# 转换结果为列表

    data['rx_bytes'] = data['rx_bytes'].diff(1)
    data['tx_bytes'] = data['tx_bytes'].diff(1)

    # data.index = pd.DatetimeIndex(data['time'])
    # data = data.resample('10s',closed='right').max()

    data.dropna(axis=0, how='any', inplace=True)

except Exception as e:
    print(e)

# 边缘图
import scipy.stats as stats
df = data.loc[:, ['time', 'rx_bytes']]
df.columns = ['time', 'data']

fig = plt.figure(figsize=(8, 6), dpi=80)
grid = plt.GridSpec(4, 4, hspace=0.5, wspace=0.2)

ax_main = fig.add_subplot(grid[:-1, :-1], xticklabels=[])
ax_right = fig.add_subplot(grid[:-1, -1], xticklabels=[], yticklabels=[])

ax_main.scatter('time', 'data',  alpha=.9, data=df)
sns.boxplot(df.data, ax=ax_right, orient="v")

print(df.describe())

# 正态分布
for i in ['rx_bytes', 'tx_bytes']:
    print(i)
    X = data[i].astype(float)
    plt.figure(figsize=(18, 8), dpi=200)
    plt.title(i+'直方图', color='dimgray')
    plt.hist(X, bins=50)
    plt.show()

    plt.figure(figsize=(18, 8), dpi=200)
    plt.title(i+'概率密度图', color='dimgray')
    sns.kdeplot(X, kernel='gau', color="g", alpha=.7)
    plt.show()

    print(stats.skew(X))  # 计算偏度
    print(stats.kurtosis(X))  # 计算峰度

df = data.loc[:, ['tx_bytes', 'rx_bytes']]


# 相关性
ts = data.loc[:, ['rx_bytes']]
ts.plot(kind="line")  # 默认绘制折线图

ts = data.loc[:, ['tx_bytes']]
ts.plot(kind="line")  # 默认绘制折线图

ts = data.loc[:, ['tx_bytes', 'rx_bytes']]
ts.plot(kind="line")  # 默认绘制折线图

# 协方差:绝对值越大,线性关系越强
data['tx_bytes'].cov(data['rx_bytes'])
# 相关系数:相关系数在-1到1之间,接近1为正相关,接近-1为负相关,0为不相关。
data['tx_bytes'].corr(data['rx_bytes'])

4.创建数据库
import os
import re
import glob
import datetime
import pandas as pd
from sqlalchemy import text, create_engine
import psycopg2
from psycopg2 import sql

import psycopg2
from psycopg2 import sql

def create_DB(schema_name, table_name, columns_info, db_config):
try:
# 创建到数据库的连接
conn = psycopg2.connect(**db_config)
cur = conn.cursor()

    # 如果不存在,则创建架构
    cur.execute(sql.SQL("CREATE SCHEMA IF NOT EXISTS {}").format(sql.Identifier(schema_name)))
    conn.commit()

    # 构造 CREATE TABLE 查询
    column_defs = [
        sql.SQL('{} {}').format(
            sql.Identifier(col_name),
            sql.SQL(columns_info[col_name]['type']) if 'type' in columns_info[col_name] else sql.SQL('TEXT')
        ) + (sql.SQL(' PRIMARY KEY') if columns_info[col_name].get('primary_key', False) else sql.SQL(''))
        for col_name in columns_info
    ]

    create_table_query = sql.SQL("""
        CREATE TABLE IF NOT EXISTS {}.{} (
            {}
        )
    """).format(
        sql.Identifier(schema_name),
        sql.Identifier(table_name),
        sql.SQL(', ').join(column_defs)
    )

    # 创建表
    cur.execute(create_table_query)
    conn.commit()

    # 删除表中的所有数据(如果有的话)
    delete_query = sql.SQL("DELETE FROM {}.{}").format(
        sql.Identifier(schema_name),
        sql.Identifier(table_name)
    )
    cur.execute(delete_query)
    conn.commit()

    print(f"成功在架构 {schema_name} 中创建表 {table_name}")

except psycopg2.Error as e:
    print(f"创建表时出错: {e}")
    if conn:
        conn.rollback()  # 回滚事务以撤销当前的更改

finally:
    if cur:
        cur.close()
    if conn:
        conn.close()

创建数据表

if name == 'main':
db_config = {
'dbname': 'postgres',
'user': '5ga-cmcc',
'password': '5ga-cmcc',
'host': 'localhost',
'port': '5432'
}
schema_name = 'public'

columns_info = {
    'time': {'type': 'timestamp without time zone'},
    'port_name': {'type': 'CHARACTER VARYING'},
    'rx_bytes': {'type': 'integer'},
    'tx_bytes': {'type': 'integer'},
    'id': {'type': 'text'}
}
table_name = 'traffic_table'

create_DB(schema_name, table_name, columns_info, db_config)

5.信息采集
import os
import time
import datetime
import pandas as pd
import schedule
import telnetlib
import paramiko
from sqlalchemy import create_engine, MetaData, Table, inspect
from sqlalchemy.orm import sessionmaker
from sqlalchemy.dialects.postgresql import insert as pg_insert

获取环境变量中的凭据

TELNET_HOST = os.getenv('TELNET_HOST', '129.60.161.169')
TELNET_USERNAME = os.getenv('TELNET_USERNAME', 'zte')
TELNET_PASSWORD = os.getenv('TELNET_PASSWORD', 'zte')
SSH_HOST = os.getenv('SSH_HOST', '10.89.164.70')
SSH_USERNAME = os.getenv('SSH_USERNAME', 'root')
SSH_PASSWORD = os.getenv('SSH_PASSWORD', 'PON@jkfx')

DATABASE_URI = os.getenv('DATABASE_URI', 'postgresql://5ga-cmcc:[email protected]:5432/postgres')
TABLE_NAME = 'traffic_table'

def get_info_telnet(host_ip, username, password):
tn = telnetlib.Telnet()
try:
tn.open(host_ip, port=23, timeout=5)
print(f'{host_ip} connected successfully!')

    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'#' not in command_result:
        print(f'{host_ip} login failed')
    else:
        print(f'{host_ip} login success')

    command = "show clock"
    command = bytes(command, encoding='utf-8')
    tn.write(command + b'\r\n')
    run_time = tn.read_until(b'#')
    run_time = re.findall(r"\d+:\d+:\d+\s+\w+\s+\w+\s+\w+\s+\d+\s+2024", run_time.decode('GB18030'))[0]

    command = "show ip interface brief"
    command = bytes(command, encoding='utf-8')
    tn.write(command + b'\n')
    time.sleep(1)

    result_list = []
    while True:
        command_result = tn.read_very_eager().decode('ascii')
        result_list.append(command_result)
        if re.findall(r"--More--", command_result.strip()):
            tn.write(b" ")
        elif re.findall(r"#", command_result.strip()):
            break
        else:
            time.sleep(0.05)

    result_str = "\n".join(result_list)
    list_str = result_str.split('\n')

    pd_result = pd.DataFrame()
    list_temperature_vec = []
    for line in list_str:
        if "Interface" in line:
            new_columns = re.split(r'\s+', line.strip())
            new_columns = new_columns[:7]
        elif re.match(r'\w+gei.+\s+.+\s+.+\s+.+\s+.+\s+.+\s+.+', line.strip()):
            list_find_str = re.split(r'\s+', line.strip())
            list_temperature_vec.append(list_find_str)

    pd_result = pd.DataFrame(list_temperature_vec, columns=new_columns)
    pd_result = pd_result[pd_result['Phy'] == 'up']

    pd_output = pd.DataFrame()
    for check_port in pd_result['Interface']:
        dict_output = {
            "port_name": check_port,
            "time": run_time
        }

        command = f"show interface {check_port}"
        command = bytes(command, encoding='utf-8')
        tn.write(command + b'\n')
        time.sleep(1)

        result_list = []
        while True:
            command_result = tn.read_very_eager().decode('ascii')
            result_list.append(command_result)
            if re.findall(r"--More--", command_result.strip()):
                tn.write(b" ")
            elif re.findall(r"#", command_result.strip()):
                break
            else:
                time.sleep(0.05)

        result_str = "\n".join(result_list)
        rx_bytes = int(re.search(r'In_Bytes\s+(\d+)', result_str).group(1))
        tx_bytes = int(re.search(r'E_Bytes\s+(\d+)', result_str).group(1))
        dict_output["rx_bytes"] = rx_bytes
        dict_output["tx_bytes"] = tx_bytes
        pd_output = pd.concat([pd_output, pd.DataFrame.from_dict([dict_output])], ignore_index=True)

    pd_output['time'] = pd.to_datetime(pd_output['time']).dt.strftime('%Y-%m-%d %H:%M:%S')
    pd_output["id"] = pd_output["port_name"] + '_' + pd_output["time"]

    tn.close()
    return pd_output

except Exception as e:
    print(f"Error: {e}")
    return None

def database_write(pd_data):
engine = create_engine(DATABASE_URI)
metadata = MetaData()
table = Table(TABLE_NAME, metadata, autoload_with=engine)
Session = sessionmaker(bind=engine, autocommit=False)
session = Session()

try:
    pd_same_period = pd_data.fillna(value=0)
    dict_rows = pd_same_period.to_dict('records')

    stmt = pg_insert(table)
    primary_keys = [key.name for key in inspect(table).primary_key]
    stmt = stmt.on_conflict_do_update(
        index_elements=primary_keys,
        set_={key: value for key, value in stmt.excluded.items()}
    )
    session.execute(stmt, dict_rows)
    session.commit()
except Exception as e:
    session.rollback()
    print(f"Error saving data to database: {e}")
finally:
    session.close()

def monitor_task():
pd_output = get_info_telnet(TELNET_HOST, TELNET_USERNAME, TELNET_PASSWORD)
if pd_output is not None:
database_write(pd_output)

if name == 'main':
schedule.every(10).seconds.do(monitor_task)
while True:
schedule.run_pending()
time.sleep(1)
6.信息采集——多远
import os
import time

import pandas as pd
import re
import glob
import numpy as np

import telnetlib
import threading

def do_telnet(host_ip, path, username, password):

# path = r'D:\Users\10079494.A24808550\Desktop\信通院python培训\\'
# host_ip = r'129.60.161.169'
# username = 'zte'
# password = 'zte'

tn = telnetlib.Telnet()
try:

    tn.open(host_ip, port=23, timeout=5)
    print('%s connected ssuccess !' % host_ip)

    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'#' not in command_result:
        print('%s登录失败' % host_ip)
    else:
        print('%s登录成功' % host_ip)

except:

    print('%s网络连接失败' % host_ip)

command = "show clock"
command = bytes(command, encoding='utf-8')
tn.write(command + b'\r\n')
run_time = tn.read_until(b'#')
run_time = re.findall(r"\d+:\d+:\d+\s+\w+\s+\w+\s+\w+\s+\d+\s+2024", run_time.decode('GB18030'))[0]

command = "show ip ospf neighbor detail"
command = bytes(command, encoding='utf-8')
tn.write(command + b'\n')
time.sleep(1)

result_list = []
while (True):
    command_result = tn.read_very_eager().decode('ascii')
    # print(command_result)
    result_list.append(command_result)
    if re.findall(r"--More--", command_result.strip()):
        tn.write(b" ")

    elif re.findall(r"#", command_result.strip()):
        break
    else:
        time.sleep(0.05)
        continue

result_str = "\n".join(result_list)

dict_ouput = {}

dict_ouput["host_ip"] = host_ip
dict_ouput["time"] = run_time

startpattern = re.compile(r'OSPF Router with ID (.+)')
strtext = re.search(startpattern, str(result_str)).group(1)
dict_ouput["OSPF Router with ID"] = strtext

startpattern = re.compile(r'Neighbor\s+(\d+.\d+.\d+.\d+)')
strtext = re.search(startpattern, str(result_str)).group(1)
dict_ouput["Neighbor"] = strtext

startpattern = re.compile(r'In the area\s+(.+)')
strtext = re.search(startpattern, str(result_str)).group(1)
dict_ouput["area"] = strtext

startpattern = re.compile(r'State\s+(\w+), ')
strtext = re.search(startpattern, str(result_str)).group(1)
dict_ouput["State"] = strtext

pd_output = pd.DataFrame.from_dict([dict_ouput])

pd_output['time'] = pd.to_datetime(pd_output['time'])
pd_output['time'] = pd_output['time'].apply(lambda x: x.strftime('%Y-%m-%d %H:%M:%S'))

pd_output.to_csv(path+os.sep+r'ospf'+'-'+str(host_ip)+'.csv', index=None, encoding='gb18030')

tn.close()

def job_get_info(path):

list_ip = ['129.60.161.169', '129.60.161.170']
username = 'zte'
password = 'zte'

print("Begin......%s" % time.ctime())
st = time.time()

for i in range(len(list_ip)):
    t = threading.Thread(target=do_telnet, args=(list_ip[i], path, username, password,))
    t.start()

print('time cost:', time.time()-st)

if name == 'main':
path = r'D:\Users\10079494.A24808550\Desktop\信通院python培训\'
job_get_info(path)

file_list = glob.glob(os.path.join(os.path.abspath(path), r'ospf*.csv'))
pd_data_o = pd.DataFrame()
for file in file_list:
    try:
        pd_sheet = pd.read_csv(file, encoding='gb18030', doublequote=False,
                               converters={u'code': str}, engine="python")
    except:
        print('读取异常')
    pd_data_o = pd.concat([pd_data_o, pd_sheet], axis=0)

`

标签:network,area,最终,交换机,command,result,pd,import,相关
From: https://www.cnblogs.com/tjrk/p/18453786/show_ip_interface_brief

相关文章

  • 虚拟存储器的相关知识
    题目考查的是虚拟存储器的相关知识。虚拟存储器的概念虚拟存储器是一种内存管理技术,它允许计算机使用比物理内存(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<新产品密钥>请将<新产品密钥>替换为您要升......
  • MATLAB两类栅格数据之间的相关性计算
    两类栅格数据之间的相关性计算(输出为tif影像)栅格数据做相关性分析前的预处理(批量定义投影、栅格投影、重采样)栅格影像行列号需要一致,行列号不一致可以在ArcGIS中批量处理:1.重采样2.裁剪右键空白环境设置处理完毕后,进行相关分析。Matlab代码-年[a,R]=geotiffread(......
  • 统计学(十三)——相关分析
    相关分析是用于研究多个变量之间相互关系的统计方法,最早由英国统计学家卡尔·皮尔逊(KarlPearson)于1896年提出。皮尔逊通过对变量间线性关系的深入研究,提出了“皮尔逊相关系数”(PearsonCorrelationCoefficient),标志着相关分析方法的诞生。随着统计学的发展,相关分析逐渐扩展,形成......
  • jvm相关命令
    jpsjps打印当前java进程jinfojinfo进程id,获取当前java进程的jvm参数jinfo-flagPrintGC进程id查看当前java进程是否开启打印GC的选项jinfo-flags进程id查看当前java进程的所有jvm配置参数jinfo-flag+PrintGC进程id为当前java进程开启打印gc日志 jmapjmap-......
  • F5负载均衡系列教程七【F5高可用相关知识】
    一、failover相关知识点1、networkfailover和hardwiredfailover的区别hardwiredfailover只能用于active/standby架构,无法用于active/active架构和viprion或者F5的虚拟机中,因为这个是需要用硬件线路连接两台F5设备;networkfailover可以用于各类2台设备以上的F5双机部署中;F......
  • 正则表达式和通配符及相关linux命令实操
    正则表达式和通配符含义是完全不同的 正则表达式基本组成: 单引号与双引号在命令中使用单引号,不转义引号内容,原样输出;使用双引号,转义引号内容*并非适用于所有命令 逻辑测试语句&&||!a&&ba执行成功才执行ba||ba执行失败才执行b!aa执行结果取反 》......