Python數據處理——re庫與pydantic的使用總結與實戰,處理采集到的思科ASA防火墻設備信息

目錄

Python正則表達式re庫的基本用法

引入re庫

各函數功能

總結

使用方法舉例

正則表達式語法與書寫方式

正則表達式的常用操作符

思科ASA防火墻數據

數據1

數據2

書寫正則表達式

Python中pydantic的使用

導入基礎數據模板

根據數據采集目標定義Pydantic數據類型

數據分析采集函數?


Python正則表達式re庫的基本用法

引入re庫

import re

各函數功能

函數用法
re.match()從字符串起始位置用正則表達式進行數據匹配,匹配到一個數據立即結束并返回第一個匹配到的結果,返回一個Match object對象
re.search()從字符串起始位置用正則表達式進行數據匹配,返回一個Match object對象,含有第一個匹配到數據的位置
re.findall()從字符串起始位置用自定義的正則表達式進行數據匹配,一直嘗試匹配到字符串結束,返回匹配到的所有子串,是一個列表
re.split()從字符串起始位置用自定義的正則表達式進行數據匹配,一直嘗試匹配到字符串結束,將字符串按正則表達式匹配到的結果進行分割,返回被分割的子串,是一個列表
re.sub()從字符串起始位置用自定義的正則表達式進行數據匹配,一直嘗試匹配到字符串結束,將字符串中按正則表達式匹配到的子串全部替換為自定義的內容,返回被替換后的字符串
re.finditer()從字符串起始位置用自定義的正則表達式進行數據匹配,一直嘗試匹配到字符串結束,返回一個callable_iterator object對象,可以被迭代,里面每個數據是Match object對象

總結

其實在數據處理中我使用re.search()居多,在使用上也很符合查找內容的慣性思維,把需要采集的數據拆分書寫成一個個短小的正則表達式,寫出的代碼也容易維護,缺點是會對字符串進行多次匹配,會浪費資源,如果設涉及大量數據的分析采集推薦使用re.match()或者是混合使用其他函數,并書寫單個較長的正則表達式可以達到節省資源的目的

使用方法舉例

data = re.match(正則表達式,需要處理的字符串,匹配選項)

在Python中正則表達式的格式為:r'...正則表達式內容...'

例如data = re.match(r'[0-9]', '123')

正則表達式語法與書寫方式

正則表達式的常用操作符

其余可自行搜索用法,本文主要涉及這幾個

符號說明
.匹配除換行符(\n、\r)之外的任何單個字符
\d匹配一個數字,等價于[0-9]
\D匹配一個任何非數字字符,等價于[^0-9]
\s匹配一個任何空白字符,如空格
\S匹配一個任何非空白字符
\n匹配一個換行符
*匹配前一個字符0次或無限次
+匹配前一個字符1次或無限次
()用于標明匹配組,方便用一個正則表達式匹配多個內容

在學習如何書寫正則表達式之前需要先了解下需要處理的數據

思科ASA防火墻數據

數據1

用Python腳本連接思科ASA防火墻執行如下命令獲取(此文章不介紹如何采集數據,數據均為樣例,和真實環境也會有出入)

show interface ip brief

?回顯內容

Interface              IP-Address      OK? Method Status                Protocol
Ethernet0/0            192.168.1.1     YES manual up                    up
Ethernet0/1            10.1.1.1        YES manual up                    up

數據2

執行命令?

show interface detail

回顯內容?

Interface Ethernet0 "outside", is up, line protocol is upHardware is i82558, BW 100 Mbps, DLY 100 usecAuto-Duplex(Full-duplex), Auto-Speed(100 Mbps)Input flow control is unsupported, output flow control is unsupportedMAC address 001e.4f9c.2345, MTU 1500IP address 172.16.0.1, subnet mask 255.255.255.128132463 packets input, 9245212 bytes, 0 no bufferReceived 24 broadcasts, 0 runts, 0 giants0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored, 0 abort0 pause input, 0 resume input0 L2 decode drops238982 packets output, 15789347 bytes, 0 underruns0 pause output, 0 resume output0 output errors, 0 collisions, 0 interface resets0 babbles, 0 late collisions, 0 deferred0 lost carrier, 0 no carrier0 input reset drops, 0 output reset dropsinput queue (curr/max packets): hardware (0/1) software (0/8)output queue (curr/max packets): hardware (0/9) software (0/1)Traffic Statistics for "outside":132463 packets input, 9245212 bytes238982 packets output, 15789347 bytes3258 packets dropped1 minute input rate 2 pkts/sec,  110 bytes/sec1 minute output rate 7 pkts/sec,  980 bytes/sec1 minute drop rate, 0 pkts/sec5 minute input rate 3 pkts/sec,  150 bytes/sec5 minute output rate 8 pkts/sec,  1012 bytes/sec5 minute drop rate, 0 pkts/secControl Point Interface States:Interface number is 1Interface config status is activeInterface state is activeInterface Ethernet1 "inside", is up, line protocol is upHardware is i82558, BW 100 Mbps, DLY 100 usecAuto-Duplex(Full-duplex), Auto-Speed(100 Mbps)Input flow control is unsupported, output flow control is unsupportedMAC address 001e.4f9c.6789, MTU 1500IP address 192.168.10.1, subnet mask 255.255.255.0204892 packets input, 14235129 bytes, 0 no bufferReceived 18 broadcasts, 0 runts, 0 giants0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored, 0 abort0 pause input, 0 resume input0 L2 decode drops174562 packets output, 20982145 bytes, 0 underruns0 pause output, 0 resume output0 output errors, 0 collisions, 0 interface resets0 babbles, 0 late collisions, 0 deferred0 lost carrier, 0 no carrier0 input reset drops, 0 output reset dropsinput queue (curr/max packets): hardware (0/1) software (0/10)output queue (curr/max packets): hardware (2/10) software (0/1)Traffic Statistics for "inside":204892 packets input, 14235129 bytes174562 packets output, 20982145 bytes5124 packets dropped1 minute input rate 4 pkts/sec,  360 bytes/sec1 minute output rate 6 pkts/sec,  890 bytes/sec1 minute drop rate, 1 pkts/sec5 minute input rate 5 pkts/sec,  480 bytes/sec5 minute output rate 7 pkts/sec,  910 bytes/sec5 minute drop rate, 0 pkts/secControl Point Interface States:Interface number is 2Interface config status is activeInterface state is active

書寫正則表達式

先來一個簡單的例子,在執行了show interface ip brief后會顯示出接口狀態和其ip地址等信息

Interface              IP-Address      OK? Method Status                Protocol
Ethernet0/0            192.168.1.1     YES manual up                    up
Ethernet0/1            10.1.1.1        YES manual up                    up

?現在假設我只對接口名稱和其對應的ip地址感興趣,想要用正則表達式將他們提取出來可以使用如下正則表達式,這個表達式還有一些小瑕疵,下面來拆解看一下他的含義:

推薦正則表達式輔助書寫和練習的工具:regex101: build, test, and debug regex

(\S+)\s*(\S+).*?

其中被"()"括起來的內容為我們想要捕獲的數據,獲取第一個"()"中的內容可對返回的對象使用.group(1)方法來獲取以此類推獲取第二個可用.group(2)來獲取

\S匹配一個任何非空白字符,后面添加“+”符號代表連續匹配1個以上的非空白字符:

\s匹配一個任何空白字符,如空格,后面加“*”代表連續匹配0個以上的非空白字符:

將這兩者組合起來:

發現除了名稱和ip之外還匹配到了其他內容,可以在后面加上“.*”直接代替其余內容直到出現換行符\n:

發現還有一個小細節沒考慮到,會匹配到上面的描述字段“Interface” 、“IP-Address”,這時可以觀察感想要匹配數據的特征來做一個排除,“Ethernet0/0”可以拆分成多個字符+一個數字的形式,即拆分成:“Ethernet0/”和“0”,其余數據也適用,都可以堪稱一個字符+結尾一個數字的格式,這時可以做一下修改,把“(\S+)”修改為“(\S+\d)”:

這樣就可以成功獲取到想要的數據了,可以編寫python代碼來試驗一下:

import redata = """
Interface              IP-Address      OK? Method Status                Protocol
Ethernet0/0            192.168.1.1     YES manual up                    up
Ethernet0/1            10.1.1.1        YES manual up                    up
"""interface_match = re.search(r'(\S+\d)\s*(\S+).*', data)print(interface_match.group(1))
print(interface_match.group(2))

輸出結果:

?

re.search方法會在查找到第一個數據后停止匹配,返回第一次匹配到的結果,如果想要捕獲所有的Interface數據,可以先將data按行進行分割再進行匹配:

import redata = """
Interface              IP-Address      OK? Method Status                Protocol
Ethernet0/0            192.168.1.1     YES manual up                    up
Ethernet0/1            10.1.1.1        YES manual up                    up
"""data_list = data.split('\n')
for line in data_list:interface_match = re.search(r'(\S+\d)\s*(\S+).*', line)if interface_match:print(interface_match.group(1))print(interface_match.group(2))

輸出結果:

?

Python中pydantic的使用

導入基礎數據模板

from pydantic import BaseModel

一個簡單的例子

pydantic在python開發中可以將數據類型明確,也方便對數據的校驗

from pydantic import BaseModelclass User(BaseModel):id: intname: strpermission: list[str]user = User(id=123456, name='admin',permission=['can_add_student','can_edit_student'])print(user)

根據數據采集目標定義Pydantic數據類型

# 定義Pydantic數據類型
class Count(BaseModel):packets: intpackets_rate: strbytes: intbytes_rate: strclass Input(Count):passclass Output(Count):passclass Dropped(Count):passclass InterfaceStatus(BaseModel):input_status: Inputoutput_status: Outputdrop_status: Droppedclass InterfaceBaseInfo(BaseModel):name: strstatus: strprotocol_status: strip_address: strsubnet_mask: strmac_address: strbandwidth: strdelay: strmtu: inthardware_type: strclass Interface(BaseModel):base_info: InterfaceBaseInfodetail_info: InterfaceStatusclass ASAData(BaseModel):outside_interface: Interfaceinside_interface: Interface

數據分析采集函數?

和上面的思路一樣,只是多了很多需要匹配的數據

def get_asa_data():# 聲明interfaces = {}# 處理interface_detail返回數據for paragraph in interface_detail.split("Interface"):if not paragraph.strip():continue# 正則匹配base_infoname_match = re.search(r'(\S+)\s"(\S+)",', paragraph)mac_mtu_match = re.search(r'MAC\saddress\s+(\S+),\sMTU\s(\d+)', paragraph)ip_match = re.search(r'IP\saddress\s(\S+),.*mask\s(\S+)', paragraph)hardware_match = re.search(r'Hardware\sis\s(.*),\sBW\s(.*),\sDLY\s(.*)', paragraph)if not name_match or not mac_mtu_match or not ip_match or not hardware_match:continuebase_info = {"name": name_match.group(1),"status": "None",  # 先做初始化,后續再從interface_ip_brief中獲取"protocol_status": "None","ip_address": ip_match.group(1),"subnet_mask": ip_match.group(2),"mac_address": mac_mtu_match.group(1),"bandwidth": hardware_match.group(2),"delay": hardware_match.group(3),"mtu": int(mac_mtu_match.group(2)),"hardware_type": hardware_match.group(1),}# 正則匹配detail_infoinput_match = re.search(r'(\d+)\spackets\sinput,\s(\d+)\sbytes', paragraph)input_rate_match = re.search(r'5\sminute\sinput\srate\s(.*),\s+(.*)', paragraph)output_match = re.search(r'(\d+)\spackets\soutput,\s(\d+)\sbytes', paragraph)output_rate_match = re.search(r'5\sminute\soutput\srate\s(.*),\s+(.*)', paragraph)drop_match = re.search(r'(\d+)\spackets\sdropped', paragraph)drop_rate_match = re.search(r'5\sminute\sdrop\srate,\s(.*)', paragraph)detail_info = {"input_status": Input(packets = int(input_match.group(1)) if input_match else -1,bytes = int(input_match.group(2)) if input_match else -1,packets_rate = input_rate_match.group(1) if input_rate_match else "None",bytes_rate = input_rate_match.group(2) if input_rate_match else "None",),"output_status": Output(packets = int(output_match.group(1)) if output_match else -1,bytes = int(output_match.group(2)) if output_match else -1,packets_rate = output_rate_match.group(1) if output_rate_match else "None",bytes_rate = output_rate_match.group(2) if output_rate_match else "None",),"drop_status": Dropped(packets = int(drop_match.group(1)) if drop_match else -1,bytes = -1,packets_rate = drop_rate_match.group(1) if drop_rate_match else "None",bytes_rate = "None",),}interface_name = name_match.group(2)interfaces[interface_name] = Interface(base_info=InterfaceBaseInfo(**base_info),detail_info=InterfaceStatus(**detail_info),)# 處理interface_ip_brie返回數據for line in interface_ip_brief.strip().split("\n"):match = re.search(r'(\S+)\s+(\S+)\s+\S+\s+\S+\s+(\S+)\s+(\S+)', line)if match:name, ip, status, protocol_status = match.groups()for interface in interfaces.values():if interface.base_info.ip_address == ip:interface.base_info.status = statusinterface.base_info.protocol_status = protocol_statusasa_data = ASAData(outside_interface=interfaces.get("outside"),inside_interface=interfaces.get("inside"),)# 將數據格式化為json返回return(asa_data.json())

?打印輸出結果

# 打印輸出結果
print(get_asa_data())

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/64041.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/64041.shtml
英文地址,請注明出處:http://en.pswp.cn/web/64041.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Yolo11改進策略:Head改進|DynamicHead,利用注意力機制統一目標檢測頭部|即插即用

摘要 論文介紹 本文介紹了一種名為DynamicHead的模塊,該模塊旨在通過注意力機制統一目標檢測頭部,以提升目標檢測的性能。論文詳細闡述了DynamicHead的工作原理,并通過實驗證明了其在COCO基準測試上的有效性和效率。 創新點 DynamicHead模塊的創新之處在于它首次嘗試在一…

`we_chat_union_id IS NOT NULL` 和 `we_chat_union_id != ‘‘` 這兩個條件之間的區別

文章目錄 1、什么是空字符串?2、兩個引號之間加上空格 好的,我們來詳細解釋一下 we_chat_union_id IS NOT NULL 和 we_chat_union_id ! 這兩個條件之間的區別,以及它們在 SQL 查詢中的作用: 1. we_chat_union_id IS NOT NULL 含…

如何利用AWS監聽存儲桶并上傳到tg bot

業務描述: 需要監聽aws的存儲中的最新消息,發送新的消息推送到指定tg的頻道。 主要流程: 1.上傳消息到s3存儲桶(不做具體描述) 2.通過aws的lambda監聽s3存儲桶的最新消息(txt文件) 3.將txt文件…

HarmonyOS NEXT 實戰之元服務:靜態案例效果---查看國內航班服務

背景: 前幾篇學習了元服務,后面幾期就讓我們開發簡單的元服務吧,里面豐富的內容大家自己加,本期案例 僅供參考 先上本期效果圖 ,里面圖片自行替換 效果圖1完整代碼案例如下: Index代碼 import { authen…

Windows11家庭版啟動Hyper-V

Hyper-V 是微軟的硬件虛擬化產品,允許在 Windows 上以虛擬機形式運行多個操作系統。每個虛擬機都在虛擬硬件上運行,可以創建虛擬硬盤驅動器、虛擬交換機等虛擬設備。使用虛擬化可以運行需要較舊版本的 Windows 或非 Windows 操作系統的軟件,以…

為什么深度學習和神經網絡要使用 GPU?

為什么深度學習和神經網絡要使用 GPU? 本篇文章的目標是幫助初學者了解 CUDA 是什么,以及它如何與 PyTorch 配合使用,更重要的是,我們為何在神經網絡編程中使用 GPU。 圖形處理單元 (GPU) 要了解 CUDA,我們需要對圖…

每天五分鐘機器學習:核函數

本文重點 在學習支持向量機算法之前,我們要繼續學習一些數學基礎,本文我們將學習核函數的概念。當數據線性不可分的時候,此時就需要核函數出場了,它可以將低維不可分的數據映射到高維可分數據,此時就可以完成數據分類了。 核函數的定義 核函數K(x, y)定義為兩個數據點x…

MaaS(Model as a Service)

1.MasS是什么? Model as a Service(MaaS)是一種云計算服務模式,它允許用戶通過互聯網訪問和使用機器學習模型,而不需要自行構建和維護這些模型。MaaS提供了模型的托管、管理和監控,使用戶能夠專注于應用程…

圖像處理-Ch7-快速小波變換和小波包

個人博客!無廣告觀看,因為這節內容太多了,有點放不下,分了三節 文章目錄 快速小波變換(The Fast Wavelet Transform)與兩頻段子帶編譯碼系統的關系例:計算一維小波變換 一維快速小波反變換例:計算一維小波…

KAFKA 權威指南筆記(一)究竟應該配置多少個BROKER?

一個KAFKA集群需要多少個BROKER? 一個單獨的Kafka服務器被叫做BROKER,BROKER可以處理數千個分區以及每秒百萬級別的消息量。由BROKER組成了“集群”(其中由集群控制器角色的BROKER是從成員中選舉出來的,負責控制管理工作&#xf…

【ES6復習筆記】函數參數的默認值(6)

在ES6中,函數參數默認值是一個非常有用的特性,它允許你在定義函數時為參數指定一個默認值。如果在調用函數時沒有提供相應的參數值,那么函數將使用默認值。 1. 形參初始值 具有默認值的參數,一般位置要靠后。這是一個潛規則&…

WebRtc webrtc-streamer部署

文章目錄 本文檔只是為了留檔方便以后工作運維,或者給同事分享文檔內容比較簡陋命令也不是特別全,不適合小白觀看,如有不懂可以私信,上班期間都是在得 WebRtc webrtc-streamer 部署 docker run -p 8000:8000 -it mpromonet/webrt…

Spring Boot中冪等性的應用

在 Spring Boot 中,冪等性是實現分布式系統設計和接口調用的一個重要概念,尤其在高并發、分布式環境下,確保接口重復調用不會引發系統數據異常至關重要。 冪等性概念 冪等性(Idempotence)是指一次請求和重復多次請求…

leetcode 7. 整數反轉

class Solution { public: int reverse(int x) { long long n0; if(x0) return 0; while(x%100) { xx/10; } while(x!0) { nn*10x%10; xx/10; } if(n<-2147483648||n>2147483647) return 0; return n; } };

[項目][boost搜索引擎#4] cpp-httplib使用 log.hpp 前端 測試及總結

目錄 編寫http_server模塊 1. 引入cpp-httplib到項目中 2. cpp-httplib的使用介紹 3. 正式編寫http_server 九、添加日志到項目中 十、編寫前端模塊 十一. 詳解傳 gitee 十二、項目總結 項目的擴展 寫在前面 [項目詳解][boost搜索引擎#1] 概述 | 去標簽 | 數據清洗 |…

xxl-job 簡單的入門到實戰

本文是參考官方文檔自己實踐一次&#xff0c;純享版&#xff0c;大致也是作者邊寫博客邊去跟著官方文檔實現 一、前期準備 1、官網地址 GitHub地址&#xff1a; GitHub - xuxueli/xxl-job: A distributed task scheduling framework.&#xff08;分布式任務調度平臺XXL-JOB&…

Centos7, 使用yum工具,出現 Could not resolve host: mirrorlist.centos.org

在 CentOS 7 中使用 yum 工具時&#xff0c;如果出現 "Could not resolve host: mirrorlist.centos.org" 的錯誤&#xff0c;通常是因為默認的鏡像源無法訪問。以下是一些常用的解決方法&#xff1a; 檢查網絡連接&#xff1a;首先使用 ping 命令測試網絡連接是否正常…

【教程】通過Docker運行AnythingLLM

轉載請注明出處&#xff1a;小鋒學長生活大爆炸[xfxuezhagn.cn] 如果本文幫助到了你&#xff0c;歡迎[點贊、收藏、關注]哦~ 官方教程&#xff1a;Local Docker Installation ~ AnythingLLM 1、先創建一個目錄用于保存anythingllm的持久化文件&#xff1a; sudo mkdir /app su…

若依(RuoYi-Vue)+Flowable工作流前后端整合教程

此教程適合若依前后端分離項目&#xff0c;其他項目可以在擴展列表中進行查找。 近期公司里需要對很久以前的RuoYi-Vue前后端分離項目擴展出flowable的功能&#xff0c;當然這個重任也是落在了我的身上&#xff08;不然也不會有這篇文章&#xff09;&#xff0c;然后我在官網看…

ubuntu 網絡管理--NetworkManager

ubuntu 網絡管理--NetworkManager 1 介紹2 NetworkManager 命令2 nmcli 命令顯示可用的wifi AP連接wifi檢查網絡連接 ?? 如何刪除刪除網絡連接查看設備狀態添加一個新的以太網連接設置靜態 IP 地址啟用并測試連接添加新的wifi連接 3 其他命令參考 1 介紹 NetworkManager 是標…