python遍历所有的txt文件中指定命令输出信息
各位大佬好,python小白第一次发帖求助。如题,就是我有多个这种txt文件,然后我想提取从display esn命令输出的回显到display version这中间的部分,请教各位大佬应该怎么编写python脚本?HRP_S<HWFW66-IB11-FW2>display elabel
/$BoardIntegrationVersion=3.0
HRP_S<HWFW66-IB11-FW2>display esn
ESN of master:18923899898
HRP_S<HWFW66-IB11-FW2>display security-policy rule all
Total:1
7 网络管理 enable permit
HRP_S<HWFW66-IB11-FW2>display security-policy rule all | include telnet
HRP_S<HWFW66-IB11-FW2>display security-policy rule all | include ssh
rule name 访问local
source-zone trust
destination-zone local
source-address address-set Net_MGT
destination-address address-set ip_163.224.37.56/31
service icmp
service icmpv6
service ssh
service tcp_8443
action permit
HRP_S<HWFW66-IB11-FW2>display security-policy rule all | include 3389
HRP_S<HWFW66-IB11-FW2>display nat-policy rule all
2022-11-11 18:50:05.970 +08:00
Total:1
RULE IDRULE NAME STATE ACTION HITS
-------------------------------------------------------------------------------
0 default enable no-nat 696320
-------------------------------------------------------------------------------
HRP_S<HWFW66-IB11-FW2>display version
Huawei Versatile Routing Platform Software
VRP (R) Software, Version 5.170 (USG6600E V600R007C00SPC200)
可以使用Python的文件处理功能逐行读取文本,使用正则表达式匹配需要提取的部分。提取出每个文件中display esn和display version之间的部分,并将其写入一个新文件中:
```
import re
#正则表达式
pattern = re.compile(r"display esn\n([\s\S]*)display version")
# 处理多个文件
for filename in ["file1.txt", "file2.txt", "file3.txt"]:
with open(filename, "r") as f_in, open("output.txt", "a") as f_out:
# 读取整个文件并进行匹配
content = f_in.read()
match = pattern.search(content)
if match:
# 写入匹配结果
f_out.write(match.group(1))
```
结果会输出到 output.txt中 厉害。。。佩服 dusagu 发表于 2023-3-7 09:59
可以使用Python的文件处理功能逐行读取文本,使用正则表达式匹配需要提取的部分。提取出每个文件中disp ...
感谢大佬
页:
[1]