交换机相关最终

cnblogs 2024-10-09 11:39:00 阅读 67

  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:

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

password='zte'code>

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

network_config='network p2p'code>

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')code>

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')code>

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

# 转换结果为列表

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

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

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")code>

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')code>

plt.hist(X, bins=50)

plt.show()

plt.figure(figsize=(18, 8), dpi=200)

plt.title(i+'概率密度图', color='dimgray')code>

sns.kdeplot(X, kernel='gau', color="g", alpha=.7)code>

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") # 默认绘制折线图code>

ts = data.loc[:, ['tx_bytes']]

ts.plot(kind="line") # 默认绘制折线图code>

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

ts.plot(kind="line") # 默认绘制折线图code>

# 协方差:绝对值越大,线性关系越强

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:5ga-cmcc@127.0.0.1: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')code>

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')code>

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')code>

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')code>

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')code>

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')code>

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,code>

converters={u'code': str}, engine="python")code>

except:

print('读取异常')

pd_data_o = pd.concat([pd_data_o, pd_sheet], axis=0)

`



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。