gpt4 book ai didi

python - 在文本文件中查找所有出现的模式

转载 作者:太空宇宙 更新时间:2023-11-04 08:09:59 24 4
gpt4 key购买 nike

我有一个看起来像这样的文本文件

Nmap scan report for 192.168.2.1
Host is up (0.023s latency).
PORT STATE SERVICE
5001/tcp closed commplex-link
MAC Address: EC:1A:59:A2:84:80 (Belkin International)

Nmap scan report for 192.168.2.2
Host is up (0.053s latency).
PORT STATE SERVICE
5001/tcp closed commplex-link
MAC Address: 94:35:0A:F0:47:C2 (Samsung Electronics Co.)

Nmap scan report for 192.168.2.3
Host is up (0.18s latency).
PORT STATE SERVICE
5001/tcp filtered commplex-link
MAC Address: 00:13:CE:C0:E5:F3 (Intel Corporate)

Nmap scan report for 192.168.2.6
Host is up (0.062s latency).
PORT STATE SERVICE
5001/tcp closed commplex-link
MAC Address: 90:21:55:7D:53:4F (HTC)

我想找到所有关闭(未过滤)端口 5001 的 IP。我尝试使用以下逻辑找到所有此类 IP

fp = open('nmap_op.txt').read()
ip = re.compile('([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)(.*)closed',re.S)
matched = ip.findall(fp)
for item in matched:
print item

我期待的输出是

192.168.2.1

192.168.2.2

192.168.2.6

但我没有得到想要的输出。输出只是一个看起来像这样的项目:

('192.168.2.1', '\nHost is up (0.023s latency).\nPORT STATE SERVICE\n5001/tcp closed commplex-link\nMAC Address: EC:1A:59:A2:84:80 (Belkin International)\n\nNmap scan report for 192.168.2.2\nHost is up (0.053s latency).\nPORT STATE SERVICE\n5001/tcp closed commplex-link\nMAC Address: 94:35:0A:F0:47:C2 (Samsung Electronics Co.)\n\nNmap scan report for 192.168.2.3\nHost is up (0.18s latency).\nPORT STATE SERVICE\n5001/tcp filtered commplex-link\nMAC Address: 00:13:CE:C0:E5:F3 (Intel Corporate)\n\nNmap scan report for 192.168.2.6\nHost is up (0.062s latency).\nPORT STATE SERVICE\n5001/tcp )

我哪里错了?

解决方法:以下逻辑对我有用。如果有人有更好的答案,请告诉我。

fp = open('nmap_op.txt').read()
entries = re.split('\n\n',fp)
ip = re.compile('([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+).*?closed',re.S)
matched = []
for item in entries:
if ip.search(item):
matched.append(ip.search(item).group(1))

最佳答案

你不需要 re.S这里。 s 修饰符将点元字符 (.) 的含义从“匹配所有除外换行符 "到 "匹配所有包括换行符"。你在这里不需要那个。

第二个捕获组也不是必需的。您可以删除它以仅返回 IP:

>>> matched = re.findall('([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+).*closed', fp)
>>> matched
['192.168.2.1', '192.168.2.2', '192.168.2.6']

关于python - 在文本文件中查找所有出现的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24372017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com