正则表达式在过滤交换机lldp信息的应用举例

news/2024/9/29 17:42:12/
#include <iostream>
#include <string>
#include <regex>
#include <vector>
#include <unordered_map>
#include <sstream>
#include <unistd.h> // For usleep// 假设存在的 LOG_INFO 和 LOG_WARNING 函数
#define LOG_INFO(...) std::cout << __VA_ARGS__ << std::endl
#define LOG_WARNING(...) std::cerr << __VA_ARGS__ << std::endlclass SwitchMonitor {
public:void lldpNeighborInfoHandle();private:void writeExchangeSerialData(const std::string& command) {std::cout << "Sending command: " << command << std::endl;}std::string readExchangeSerialData() {return R"(GigabitEthernet0/0/20 has 1 neighbor(s):Neighbor index :1Chassis type   :MAC addressChassis ID     :1001-0114-0101Port ID type   :Interface namePort ID        :hhhhh1System name    :HYExpired time   :3sGigabitEthernet0/0/21 has 2 neighbor(s):Neighbor index :1Chassis type   :MAC addressChassis ID     :1004-0114-0102Port ID type   :Interface namePort ID        :CM300-PID-0001System name    :HhXSExpired time   :3sNeighbor index :2Chassis type   :MAC addressChassis ID     :1004-0113-0103Port ID type   :Interface namePort ID        :CM300-PID-0001System name    :HYXSExpired time   :3sGigabitEthernet0/0/22 has 1 neighbor(s):Neighbor index :1Chassis type   :MAC addressChassis ID     :3cc7-867d-efffPort ID type   :Interface namePort ID        :GigabitEthernet0/0/2Port description    :GigabitEthernet0/0/2System name         :FutureMatrixSystem description  :hhhhhhhFutureMatrix Versatile Routing Platform SoftwareVRP (R) software, Version 5.170 (S5735 V200R022C00SPC500)System capabilities supported   :bridge routerSystem capabilities enabled     :bridge routerManagement address type  :ipv4Management address value :192.168.1.253Expired time   :95sPort VLAN ID(PVID)  :1VLAN name of VLAN  1:VLAN 0001Auto-negotiation supported    :YesAuto-negotiation enabled      :YesOperMau   :speed(100)/duplex(Full)Power port class            :PDPSE power supported         :NoPSE power enabled           :NoPSE pairs control ability   :NoPower pairs                 :UnknownPort power classification   :UnknownLink aggregation supported:YesLink aggregation enabled :NoAggregation port ID      :0Maximum frame Size       :10232GigabitEthernet0/0/23 has 1 neighbor(s):Neighbor index :1Chassis type   :MAC addressChassis ID     :1001-0114-0104Port ID type   :Interface namePort ID        :S5730System name    :XJExpired time   :3sGigabitEthernet0/0/24 has 2 neighbor(s):Neighbor index :1Chassis type   :MAC addressChassis ID     :1004-0114-0105Port ID type   :Interface namePort ID        :PID-0005System name    :xj2Expired time   :3sNeighbor index :2Chassis type   :MAC addressChassis ID     :1004-0113-0106Port ID type   :Interface namePort ID        :PID-0006System name    :xj3Expired time   :3s)";}struct MacAddressInfo {std::string deviceType;std::string identifier;std::string board;std::string slot;std::string interface;};MacAddressInfo parseMacAddress(const std::string& mac) {return {"DeviceType", "Identifier", "Board", "Slot", "Interface"};}std::vector<std::unordered_map<std::string, std::string>> contents_;
};void SwitchMonitor::lldpNeighborInfoHandle() {std::string responseConnectInfo;writeExchangeSerialData("display lldp neighbor\n");int totalCount = 0;while (true) {usleep(10 * 1000); // 10 毫秒responseConnectInfo = readExchangeSerialData();if (responseConnectInfo.empty()) {break; // 如果没有回复,退出循环} else {std::regex pattern(R"(GigabitEthernet0/0/(\d+) has (\d+) neighbor\(s\):([\s\S]*?)(?=GigabitEthernet0/0/\d+|\Z|$))");std::smatch matches;std::string::const_iterator it(responseConnectInfo.cbegin());while (std::regex_search(it, responseConnectInfo.cend(), matches, pattern)) {std::string portToFind = matches[1].str();int neighborCount = std::stoi(matches[2].str());std::string neighborsDetails = matches[3].str();LOG_INFO("############ GigabitEthernet0/0/" << portToFind << " with " << neighborCount << " neighbor(s)" << "    neighborsDetails: " << neighborsDetails);if (neighborCount == 1) {std::regex singleNeighborPattern(R"(Neighbor index\s*:(\d+)[\s\S]*?Chassis ID\s*:\s*(\S+))");std::smatch singleNeighborMatches;if (std::regex_search(neighborsDetails, singleNeighborMatches, singleNeighborPattern)) {std::string macToFindCurrent = singleNeighborMatches[2].str();LOG_INFO("Single Neighbor Chassis ID: " << macToFindCurrent);MacAddressInfo foundInfo = parseMacAddress(macToFindCurrent);if (foundInfo.deviceType.empty()) {LOG_WARNING("Protocol MAC device, parse MAC failed, MAC: " << macToFindCurrent);} else {//xxxxx 处理信息}}} else if (neighborCount > 1) {std::regex neighborPattern(R"(Neighbor index\s*:(\d+)[\s\S]*?Chassis ID\s*:\s*(\S+))");std::smatch neighborMatches;std::string::const_iterator nIt(neighborsDetails.cbegin());while (std::regex_search(nIt, neighborsDetails.cend(), neighborMatches, neighborPattern)) {std::string macToFindCurrent = neighborMatches[2].str();LOG_INFO("multy Neighbor Chassis ID: " << macToFindCurrent);MacAddressInfo foundInfo = parseMacAddress(macToFindCurrent);if (foundInfo.deviceType.empty()) {LOG_WARNING("Protocol MAC device, parse MAC failed, MAC: " << macToFindCurrent);} else {//xxxxx 处理信息}// 更新迭代器到下一个邻居nIt = neighborMatches.suffix().first;}}totalCount++;LOG_INFO("--------------------------------------------------------------------------------------- totalCount" << totalCount);// 移动迭代器到当前匹配的末尾以搜索下一个接口it = matches.suffix().first;}usleep(10);}}
}int main() {SwitchMonitor monitor;monitor.lldpNeighborInfoHandle();LOG_INFO("$$$$$$$$$$$$$$$$$$$$ end");return 0;
}

经过了70w次近1小时的测试,,没有问题。
在这里插入图片描述


http://www.ppmy.cn/news/1532020.html

相关文章

SpringMVC4-SpringMVC获取请求参数

目录 通过ServletAPI获取&#xff08;不常用&#xff09; 通过控制器方法的形参获取请求参数 RequestParam RequestHeader CookieValue 通过POJO获取请求参数 解决获取请求参数的乱码问题 test_param.html&#xff1a; <!DOCTYPE html> <html lang"en&qu…

性能调优知识点(mysql)三

SQL底层执行原理 MySQL的内部组件结构&#xff1a;大体来说&#xff0c;MySQL 可以分为 Server 层和存储引擎层store两部分 Server层:主要包括连接器、查询缓存、分析器、优化器、执行器等&#xff0c;涵盖 MySQL 的大多数核心服务功能&#xff0c;以及所有的内置函数&#xf…

R包:VennDiagram韦恩图

加载R包 library(VennDiagram)数据 # Prepare character vectors v1 <- c("DKK1", "NPC1", "NAPG", "ERG", "VHL", "BTD", "MALL", "HAUS1") v2 <- c("SMAD4", "DKK1…

一、Spring Boot集成Spring Security之自动装配

Spring Boot集成Spring Security之自动装配介绍 一、实现功能及软件版本说明二、创建Spring Boot项目三、查看自动装配配置类四、自动装配配置类之SecurityAutoConfiguration1、SecurityAutoConfiguration部分源码2、主要作用3、SpringBootWebSecurityConfiguration3.1、Spring…

深入探讨AI 神经网络:类型、特点与创新应用

一、引言 1.1 背景 随着科技的飞速发展,人工智能已经成为当今社会的热门领域。在人工智能的发展过程中,神经网络扮演着至关重要的角色。神经网络是一种模拟人类大脑神经元结构的计算模型,它通过大量的神经元相互连接并进行信息处理,从而实现对数据的分析和预测。不同类型…

网络空间搜索引擎- FOFA的使用技巧总结

网络空间搜索引擎- FOFA的使用技巧总结 简介 FOFA是一款网络空间测绘的搜索引擎&#xff0c;旨在帮助用户以搜索的方式查找公网上的互联网资产。 FOFA的查询方式类似于谷歌或百度&#xff0c;用户可以输入关键词来匹配包含该关键词的数据。不同的是&#xff0c;这些数据不仅包…

CNN-LSTM预测 | MATLAB实现CNN-LSTM卷积长短期记忆神经网络时间序列预测

CNN-LSTM预测 | MATLAB实现CNN-LSTM卷积长短期记忆神经网络时间序列预测 目录 CNN-LSTM预测 | MATLAB实现CNN-LSTM卷积长短期记忆神经网络时间序列预测预测效果基本介绍模型描述程序设计参考资料预测效果 基本介绍 本次运行测试环境MATLAB2020b 提出一种包含卷积神经网络和长短…

C语言 | 第四章 | 常量 运算符

P 31 课后练习评讲 2022/8/24 一、题目 代码演示:第一题 #include<stdio.h>void main(){// 分析&#xff1a;使用不同的变量来保存对应的数据char name[10] "张三"; // 字符数组&#xff0c;存放字符串short age 23;float score 78.5f;char gender M; …