翼度科技»论坛 编程开发 python 查看内容

交换机相关最终

5

主题

5

帖子

15

积分

新手上路

Rank: 1

积分
15

  • 用判断语句实现所有可能场景
    `
    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)
  1.     command_result=tn.read_until(b'#',timeout=5)
  2.     if b'#' in command_result:
  3.         print(f'{host_ip} telnet success')
  4.     else:
  5.         print(f'{host_ip} telnet failed')
  6.     return tn
  7. except:
  8.     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:
  1.         match_area = re.match(r'^\s*area\s+(\d\.\d\.\d\.\d)$', i.strip())
  2.         match_interface = re.match(r'^\s*interface\s+(\w+.+)$', i.strip())
  3.         match_network = re.match(r'^\s*network\s+(\w+.+)$', i.strip())
  4.         match_redistribute = re.match(r'^\s*redistribute\s+(\w+)$', i.strip())
  5.         if match_area:
  6.             data.append({'area': match_area.group(1)})
  7.         elif match_interface:
  8.              data[-1]['interface'] = match_interface.group(1)
  9.         elif match_network:
  10.              data[-1]['network'] = match_network.group(1)
  11.         if match_redistribute:
  12.             findstr = match_redistribute.group(1)
  13.             import_list.append(findstr)
  14.     if len(import_list) > 0:
  15.         df_import = pd.DataFrame(import_list)
  16.     else:
  17.         df_import.loc[0, 0] = ''
  18.     df_import.columns = ['import']
  19.     #print(data)
  20.     df_area = pd.DataFrame(data)
  21.     # if 'area' not in df_area.columns:
  22.     #     df_area['area']=''
  23.     # if 'interface' not in df_area.columns:
  24.     #     df_area['interface']=''
  25.     # if 'network' not in df_area.columns:
  26.     #     df_area['network']=''
  27.     df = pd.concat([df_area, df_import], axis=1)
  28.     #df['host_ip'] = host_ip
  29.     print(df)
  30.     return df
  31. except:
  32.     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']
  1. username='zte'
  2. password='zte'
  3. df=pd.DataFrame()#注意不能写成df=DataFrame()
  4. df1=pd.DataFrame()
  5. df2=pd.DataFrame()
  6. #tn=telnet_login(host_ip=hosts_ip[0],username=username,password=password)
  7. df_ospf_two = pd.DataFrame()
  8. a=0
  9. for host_ip in hosts_ip:
  10.     tn=telnet_login(host_ip,username,password)
  11.     if tn:
  12.          df=get_intface_state(tn,host_ip)
  13.          for interface in interfaces:
  14.              if df[df['Interface']==interface]['Admin'].values[0]=='down':
  15.                 print(f'{interface} is admin down, please no shutdown it')
  16.              if df[df['Interface']==interface]['IP-Address'].values[0]!=planed_ip[a]:
  17.                  print(f'{interface} ip address is not {planed_ip[a]}')
  18.              a=a+1
  19.          tn.close()
  20.     else:
  21.          print('telnet failed')
  22. tn1 = telnet_login(hosts_ip[0], username, password)
  23. tn2 = telnet_login(hosts_ip[1], username, password)
  24. df1 = get_ospf_config(tn1)
  25. df2 = get_ospf_config(tn2)
  26. if 'area' not in df1.columns:
  27.     if 'interface' in df2.columns:
  28.         if interfaces[0] in df2['interface'].values:
  29.             area_config= df2[df2['interface'] == interfaces[0]]['area'].values[0]
  30.             if 'network' in df2.columns:
  31.                 network_config=df2[df2['interface']==interfaces[0]]['network'].values[0]
  32.                 print(f'router1 configuredarea:{area_config},interface:{interfaces[0]},network:{network_config}')
  33.             else:
  34.                 print(f'router 1 configured:{area_config},two router network:network p2p')
  35.         else:
  36.             area_config='0.0.0.0'
  37.             network_config='network p2p'
  38.             print(f'configured two router {area_config},{interfaces[0]},{network_config}')
  39. else:
  40.     if 'interface' in df1.columns:
  41.         if interfaces[0] in df1['interface'].values:
  42.             if 'interface' in df2.columns:
  43.                 if interfaces[0] in df2['interface'].values:
  44.                     if df1[df1['interface'] == interfaces[0]]['area'].values[0] == \
  45.                             df2[df2['interface'] == interfaces[0]]['area'].values[0]:
  46.                         if 'network' not in df1.columns:
  47.                             if 'network' in df2.columns:
  48.                                 network_config = df2[df2['interface'] == interfaces[0]]['network'].values[0]
  49.                                 print(f'router1 configured:{network_config}')
  50.                             else:
  51.                                 print('two router configured:network p2p')
  52.                         else:
  53.                             if 'network' in df2.columns:
  54.                                 if df1[df1['interface'] == interfaces[0]]['network'].values[0] != \
  55.                                         df2[df2['interface'] == interfaces[0]]['network'].values[0]:
  56.                                     network_config = df1[df1['interface'] == interfaces[0]]['network'].values[0]
  57.                                     print(f'router2 configured:{network_config}')
  58.                             else:
  59.                                 network_config = df1[df1['interface'] == interfaces[0]]['network'].values[0]
  60.                                 print(f'router2 configured:{network_config}')
  61.                     else:
  62.                         if 'network' in df1.columns:
  63.                             area_config = df1[df1['interface'] == interfaces[0]]['area'].values[0]
  64.                             network_config = df1[df1['interface'] == interfaces[0]]['network'].values[0]
  65.                             print(
  66.                                 f'router2 delete the interface adn configured_area:{area_config},{interfaces[0]},configured_network:{network_config}')
  67.                         else:
  68.                             area_config = df1[df1['interface'] == interfaces[0]]['area'].values[0]
  69.                             print(f'router1 configured:network p2p')
  70.                             print(
  71.                                 f'router2 configured_area:{area_config},{interfaces[0]},configured_network:network p2p')
  72.                 else:
  73.                     if 'network' in df1.columns:
  74.                         configured_area = df1[df1['interface'] == interfaces[0]]['area'].values[0]
  75.                         configured_network = df1[df1['interface'] == interfaces[0]]['network'].values[0]
  76.                         print(
  77.                             f'router2 configured_area:{configured_area},{interfaces[0]},configured_network:network p2p')
  78.                     else:
  79.                         configured_area = df1[df1['interface'] == interfaces[0]]['area'].values[0]
  80.                         print(
  81.                             f'router2 configured_area:{configured_area},{interfaces[0]},configured_network:network p2p')
  82.                         print(f'router1 configured:network p2p')
  83.             else:
  84.                 if 'network' in df1.columns:
  85.                     area_config = df1[df1['interface'] == interfaces[0]]['area'].values[0]
  86.                     network_config = df1[df1['interface'] == interfaces[0]]['network'].values[0]
  87.                     print(
  88.                         f'router2 configured_area:{area_config},{interfaces[0]},configured_network:{network_config}')
  89.                 else:
  90.                     area_config = df1[df1['interface'] == interfaces[0]]['area'].values[0]
  91.                     print(f'router2 configured_area:{area_config},{interfaces[0]},configured_network:network p2p')
  92.                     print(f'router1 configured:network p2p')
  93.         else:
  94.             if 'interface' in df2.columns:
  95.                 if interfaces[0] in df2['interface'].values:
  96.                     area_config = df2[df2['interface'] == interfaces[0]]['area'].values[0]
  97.                     if 'network' in df2.columns:
  98.                         network_config = df2[df2['interface'] == interfaces[0]]['network'].values[0]
  99.                         print(
  100.                             f'router1 configured_area:{area_config}, interfaces[0], configured_network:{network_config}')
  101.                     else:
  102.                         network_config = 'network p2p'
  103.                         print(
  104.                             f'router1 configured_area:{area_config}, interfaces[0], configured_network:{network_config}')
  105.                         print(f'router2  configured_network:network p2p')
  106.                 else:
  107.                     area_config = '0.0.0.0'
  108.                     network_config = 'network p2p'
  109.                     print(f'configured two router {area_config},{interfaces[0]},{network_config}')
  110.     else:
  111.         if 'interface' in df2.columns:
  112.             if interfaces[0] in df2['interface'].values:
  113.                 area_config = df2[df2['interface'] == interfaces[0]]['area'].values[0]
  114.                 if 'network' in df2.columns:
  115.                     network_config = df2[df2['interface'] == interfaces[0]]['network'].values[0]
  116.                     print(f'router1 configured_area:{area_config},{interfaces[0]},network:{network_config}')
  117.                 else:
  118.                     print(f'router 1 configured_area:{area_config},two router network:network p2p')
  119.             else:
  120.                 area_config = '0.0.0.0'
  121.                 network_config = 'network p2p'
  122.                 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):
  1. host_ip = '129.60.161.169'
  2. username = 'zte'
  3. password = 'zte'
  4. tn = telnetlib.Telnet()
  5. try:
  6.     tn.open(host_ip, port=23, timeout=5)
  7.     print('%s connected ssuccess !' % host_ip)
  8.     tn.read_until(b'Username:', timeout=5)
  9.     tn.write(username.encode('ascii') + b'\n')
  10.     tn.read_until(b'Password:', timeout=5)
  11.     tn.write(password.encode('ascii') + b'\n')
  12.     time.sleep(1)
  13.     command_result = tn.read_until(b'#', timeout=5)
  14.     if b'#' not in command_result:
  15.         print('%s登录失败' % host_ip)
  16.     else:
  17.         print('%s登录成功' % host_ip)
  18. except:
  19.     print('%s网络连接失败' % host_ip)
  20. command = "show clock"
  21. command = bytes(command, encoding='utf-8')
  22. tn.write(command + b'\r\n')
  23. run_time = tn.read_until(b'#')
  24. run_time = re.findall(r"\d+:\d+:\d+\s+\w+\s+\w+\s+\w+\s+\d+\s+2024", run_time.decode('GB18030'))[0]
  25. command = "show interface brief"
  26. command = bytes(command, encoding='utf-8')
  27. tn.write(command + b'\n')
  28. time.sleep(1)
  29. result_list = []
  30. while (True):
  31.     command_result = tn.read_very_eager().decode('ascii')
  32.     # print(command_result)
  33.     result_list.append(command_result)
  34.     if re.findall(r"--More--", command_result.strip()):
  35.         tn.write(b" ")
  36.     elif re.findall(r"#", command_result.strip()):
  37.         break
  38.     else:
  39.         time.sleep(0.05)
  40.         continue
  41. result_str = "\n".join(result_list)
  42. list_str = result_str.split('\n')
  43. pd_result = pd.DataFrame()
  44. list_temperature_vec = []
  45. for j in list_str:
  46.     regex = re.compile(r'\w+gei.+\s+.+\s+.+\s+.+\s+.+\s+.+\s+.+', re.S)
  47.     # print(regex.findall(j))
  48.     # print(len(regex.findall(j)))
  49.     if len(re.findall(r"Interface", j)) > 0:
  50.         new_columns = list_find_str = re.split(r'\s+', j)
  51.         new_columns = new_columns[0:8]
  52.     if len(regex.findall(j)) > 0:
  53.         list_find_str = regex.findall(j)[0]
  54.         list_find_str = re.split(r'\s+', list_find_str)
  55.         list_temperature_vec.append(list_find_str)
  56. pd_result = pd.DataFrame(list_temperature_vec)
  57. pd_result.columns = new_columns
  58. tn.close()
  59. return pd_result
复制代码
if name == 'main':
  1. host_ip = '129.60.161.169'
  2. username = 'zte'
  3. password = 'zte'
  4. 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()
# 转换结果为列表
  1.     data['rx_bytes'] = data['rx_bytes'].diff(1)
  2.     data['tx_bytes'] = data['tx_bytes'].diff(1)
  3.     # data.index = pd.DatetimeIndex(data['time'])
  4.     # data = data.resample('10s',closed='right').max()
  5.     data.dropna(axis=0, how='any', inplace=True)
  6. except Exception as e:
  7.     print(e)
  8. # 边缘图
  9. import scipy.stats as stats
  10. df = data.loc[:, ['time', 'rx_bytes']]
  11. df.columns = ['time', 'data']
  12. fig = plt.figure(figsize=(8, 6), dpi=80)
  13. grid = plt.GridSpec(4, 4, hspace=0.5, wspace=0.2)
  14. ax_main = fig.add_subplot(grid[:-1, :-1], xticklabels=[])
  15. ax_right = fig.add_subplot(grid[:-1, -1], xticklabels=[], yticklabels=[])
  16. ax_main.scatter('time', 'data',  alpha=.9, data=df)
  17. sns.boxplot(df.data, ax=ax_right, orient="v")
  18. print(df.describe())
  19. # 正态分布
  20. for i in ['rx_bytes', 'tx_bytes']:
  21.     print(i)
  22.     X = data[i].astype(float)
  23.     plt.figure(figsize=(18, 8), dpi=200)
  24.     plt.title(i+'直方图', color='dimgray')
  25.     plt.hist(X, bins=50)
  26.     plt.show()
  27.     plt.figure(figsize=(18, 8), dpi=200)
  28.     plt.title(i+'概率密度图', color='dimgray')
  29.     sns.kdeplot(X, kernel='gau', color="g", alpha=.7)
  30.     plt.show()
  31.     print(stats.skew(X))  # 计算偏度
  32.     print(stats.kurtosis(X))  # 计算峰度
  33. df = data.loc[:, ['tx_bytes', 'rx_bytes']]
  34. # 相关性
  35. ts = data.loc[:, ['rx_bytes']]
  36. ts.plot(kind="line")  # 默认绘制折线图
  37. ts = data.loc[:, ['tx_bytes']]
  38. ts.plot(kind="line")  # 默认绘制折线图
  39. ts = data.loc[:, ['tx_bytes', 'rx_bytes']]
  40. ts.plot(kind="line")  # 默认绘制折线图
  41. # 协方差:绝对值越大,线性关系越强
  42. data['tx_bytes'].cov(data['rx_bytes'])
  43. # 相关系数:相关系数在-1到1之间,接近1为正相关,接近-1为负相关,0为不相关。
  44. 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()
  1.     # 如果不存在,则创建架构
  2.     cur.execute(sql.SQL("CREATE SCHEMA IF NOT EXISTS {}").format(sql.Identifier(schema_name)))
  3.     conn.commit()
  4.     # 构造 CREATE TABLE 查询
  5.     column_defs = [
  6.         sql.SQL('{} {}').format(
  7.             sql.Identifier(col_name),
  8.             sql.SQL(columns_info[col_name]['type']) if 'type' in columns_info[col_name] else sql.SQL('TEXT')
  9.         ) + (sql.SQL(' PRIMARY KEY') if columns_info[col_name].get('primary_key', False) else sql.SQL(''))
  10.         for col_name in columns_info
  11.     ]
  12.     create_table_query = sql.SQL("""
  13.         CREATE TABLE IF NOT EXISTS {}.{} (
  14.             {}
  15.         )
  16.     """).format(
  17.         sql.Identifier(schema_name),
  18.         sql.Identifier(table_name),
  19.         sql.SQL(', ').join(column_defs)
  20.     )
  21.     # 创建表
  22.     cur.execute(create_table_query)
  23.     conn.commit()
  24.     # 删除表中的所有数据(如果有的话)
  25.     delete_query = sql.SQL("DELETE FROM {}.{}").format(
  26.         sql.Identifier(schema_name),
  27.         sql.Identifier(table_name)
  28.     )
  29.     cur.execute(delete_query)
  30.     conn.commit()
  31.     print(f"成功在架构 {schema_name} 中创建表 {table_name}")
  32. except psycopg2.Error as e:
  33.     print(f"创建表时出错: {e}")
  34.     if conn:
  35.         conn.rollback()  # 回滚事务以撤销当前的更改
  36. finally:
  37.     if cur:
  38.         cur.close()
  39.     if conn:
  40.         conn.close()
复制代码
创建数据表

if name == 'main':
db_config = {
'dbname': 'postgres',
'user': '5ga-cmcc',
'password': '5ga-cmcc',
'host': 'localhost',
'port': '5432'
}
schema_name = 'public'
  1. columns_info = {
  2.     'time': {'type': 'timestamp without time zone'},
  3.     'port_name': {'type': 'CHARACTER VARYING'},
  4.     'rx_bytes': {'type': 'integer'},
  5.     'tx_bytes': {'type': 'integer'},
  6.     'id': {'type': 'text'}
  7. }
  8. table_name = 'traffic_table'
  9. 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!')
  1.     tn.read_until(b'Username:', timeout=5)
  2.     tn.write(username.encode('ascii') + b'\n')
  3.     tn.read_until(b'Password:', timeout=5)
  4.     tn.write(password.encode('ascii') + b'\n')
  5.     time.sleep(1)
  6.     command_result = tn.read_until(b'#', timeout=5)
  7.     if b'#' not in command_result:
  8.         print(f'{host_ip} login failed')
  9.     else:
  10.         print(f'{host_ip} login success')
  11.     command = "show clock"
  12.     command = bytes(command, encoding='utf-8')
  13.     tn.write(command + b'\r\n')
  14.     run_time = tn.read_until(b'#')
  15.     run_time = re.findall(r"\d+:\d+:\d+\s+\w+\s+\w+\s+\w+\s+\d+\s+2024", run_time.decode('GB18030'))[0]
  16.     command = "show ip interface brief"
  17.     command = bytes(command, encoding='utf-8')
  18.     tn.write(command + b'\n')
  19.     time.sleep(1)
  20.     result_list = []
  21.     while True:
  22.         command_result = tn.read_very_eager().decode('ascii')
  23.         result_list.append(command_result)
  24.         if re.findall(r"--More--", command_result.strip()):
  25.             tn.write(b" ")
  26.         elif re.findall(r"#", command_result.strip()):
  27.             break
  28.         else:
  29.             time.sleep(0.05)
  30.     result_str = "\n".join(result_list)
  31.     list_str = result_str.split('\n')
  32.     pd_result = pd.DataFrame()
  33.     list_temperature_vec = []
  34.     for line in list_str:
  35.         if "Interface" in line:
  36.             new_columns = re.split(r'\s+', line.strip())
  37.             new_columns = new_columns[:7]
  38.         elif re.match(r'\w+gei.+\s+.+\s+.+\s+.+\s+.+\s+.+\s+.+', line.strip()):
  39.             list_find_str = re.split(r'\s+', line.strip())
  40.             list_temperature_vec.append(list_find_str)
  41.     pd_result = pd.DataFrame(list_temperature_vec, columns=new_columns)
  42.     pd_result = pd_result[pd_result['Phy'] == 'up']
  43.     pd_output = pd.DataFrame()
  44.     for check_port in pd_result['Interface']:
  45.         dict_output = {
  46.             "port_name": check_port,
  47.             "time": run_time
  48.         }
  49.         command = f"show interface {check_port}"
  50.         command = bytes(command, encoding='utf-8')
  51.         tn.write(command + b'\n')
  52.         time.sleep(1)
  53.         result_list = []
  54.         while True:
  55.             command_result = tn.read_very_eager().decode('ascii')
  56.             result_list.append(command_result)
  57.             if re.findall(r"--More--", command_result.strip()):
  58.                 tn.write(b" ")
  59.             elif re.findall(r"#", command_result.strip()):
  60.                 break
  61.             else:
  62.                 time.sleep(0.05)
  63.         result_str = "\n".join(result_list)
  64.         rx_bytes = int(re.search(r'In_Bytes\s+(\d+)', result_str).group(1))
  65.         tx_bytes = int(re.search(r'E_Bytes\s+(\d+)', result_str).group(1))
  66.         dict_output["rx_bytes"] = rx_bytes
  67.         dict_output["tx_bytes"] = tx_bytes
  68.         pd_output = pd.concat([pd_output, pd.DataFrame.from_dict([dict_output])], ignore_index=True)
  69.     pd_output['time'] = pd.to_datetime(pd_output['time']).dt.strftime('%Y-%m-%d %H:%M:%S')
  70.     pd_output["id"] = pd_output["port_name"] + '_' + pd_output["time"]
  71.     tn.close()
  72.     return pd_output
  73. except Exception as e:
  74.     print(f"Error: {e}")
  75.     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()
  1. try:
  2.     pd_same_period = pd_data.fillna(value=0)
  3.     dict_rows = pd_same_period.to_dict('records')
  4.     stmt = pg_insert(table)
  5.     primary_keys = [key.name for key in inspect(table).primary_key]
  6.     stmt = stmt.on_conflict_do_update(
  7.         index_elements=primary_keys,
  8.         set_={key: value for key, value in stmt.excluded.items()}
  9.     )
  10.     session.execute(stmt, dict_rows)
  11.     session.commit()
  12. except Exception as e:
  13.     session.rollback()
  14.     print(f"Error saving data to database: {e}")
  15. finally:
  16.     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):
  1. # path = r'D:\Users\10079494.A24808550\Desktop\信通院python培训\\'
  2. # host_ip = r'129.60.161.169'
  3. # username = 'zte'
  4. # password = 'zte'
  5. tn = telnetlib.Telnet()
  6. try:
  7.     tn.open(host_ip, port=23, timeout=5)
  8.     print('%s connected ssuccess !' % host_ip)
  9.     tn.read_until(b'Username:', timeout=5)
  10.     tn.write(username.encode('ascii') + b'\n')
  11.     tn.read_until(b'Password:', timeout=5)
  12.     tn.write(password.encode('ascii') + b'\n')
  13.     time.sleep(1)
  14.     command_result = tn.read_until(b'#', timeout=5)
  15.     if b'#' not in command_result:
  16.         print('%s登录失败' % host_ip)
  17.     else:
  18.         print('%s登录成功' % host_ip)
  19. except:
  20.     print('%s网络连接失败' % host_ip)
  21. command = "show clock"
  22. command = bytes(command, encoding='utf-8')
  23. tn.write(command + b'\r\n')
  24. run_time = tn.read_until(b'#')
  25. run_time = re.findall(r"\d+:\d+:\d+\s+\w+\s+\w+\s+\w+\s+\d+\s+2024", run_time.decode('GB18030'))[0]
  26. command = "show ip ospf neighbor detail"
  27. command = bytes(command, encoding='utf-8')
  28. tn.write(command + b'\n')
  29. time.sleep(1)
  30. result_list = []
  31. while (True):
  32.     command_result = tn.read_very_eager().decode('ascii')
  33.     # print(command_result)
  34.     result_list.append(command_result)
  35.     if re.findall(r"--More--", command_result.strip()):
  36.         tn.write(b" ")
  37.     elif re.findall(r"#", command_result.strip()):
  38.         break
  39.     else:
  40.         time.sleep(0.05)
  41.         continue
  42. result_str = "\n".join(result_list)
  43. dict_ouput = {}
  44. dict_ouput["host_ip"] = host_ip
  45. dict_ouput["time"] = run_time
  46. startpattern = re.compile(r'OSPF Router with ID (.+)')
  47. strtext = re.search(startpattern, str(result_str)).group(1)
  48. dict_ouput["OSPF Router with ID"] = strtext
  49. startpattern = re.compile(r'Neighbor\s+(\d+.\d+.\d+.\d+)')
  50. strtext = re.search(startpattern, str(result_str)).group(1)
  51. dict_ouput["Neighbor"] = strtext
  52. startpattern = re.compile(r'In the area\s+(.+)')
  53. strtext = re.search(startpattern, str(result_str)).group(1)
  54. dict_ouput["area"] = strtext
  55. startpattern = re.compile(r'State\s+(\w+), ')
  56. strtext = re.search(startpattern, str(result_str)).group(1)
  57. dict_ouput["State"] = strtext
  58. pd_output = pd.DataFrame.from_dict([dict_ouput])
  59. pd_output['time'] = pd.to_datetime(pd_output['time'])
  60. pd_output['time'] = pd_output['time'].apply(lambda x: x.strftime('%Y-%m-%d %H:%M:%S'))
  61. pd_output.to_csv(path+os.sep+r'ospf'+'-'+str(host_ip)+'.csv', index=None, encoding='gb18030')
  62. tn.close()
复制代码
def job_get_info(path):
  1. list_ip = ['129.60.161.169', '129.60.161.170']
  2. username = 'zte'
  3. password = 'zte'
  4. print("Begin......%s" % time.ctime())
  5. st = time.time()
  6. for i in range(len(list_ip)):
  7.     t = threading.Thread(target=do_telnet, args=(list_ip[i], path, username, password,))
  8.     t.start()
  9. print('time cost:', time.time()-st)
复制代码
if name == 'main':
path = r'D:\Users\10079494.A24808550\Desktop\信通院python培训\'
job_get_info(path)
  1. file_list = glob.glob(os.path.join(os.path.abspath(path), r'ospf*.csv'))
  2. pd_data_o = pd.DataFrame()
  3. for file in file_list:
  4.     try:
  5.         pd_sheet = pd.read_csv(file, encoding='gb18030', doublequote=False,
  6.                                converters={u'code': str}, engine="python")
  7.     except:
  8.         print('读取异常')
  9.     pd_data_o = pd.concat([pd_data_o, pd_sheet], axis=0)
复制代码
`

来源:https://www.cnblogs.com/tjrk/p/18453786/show_ip_interface_brief
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具