简体   繁体   English

正则表达式匹配已知字符串之前的IP地址

[英]Regex Match on IP Address Before Known String

I'm using nmap to search for hostnames and related IPs on my local (home) network. 我正在使用nmap在本地(家庭)网络上搜索主机名和相关IP。 I can pull a string that looks something like this: 我可以拉一个看起来像这样的字符串:

Starting Nmap 6.40 ( http://nmap.org ) at 2014-02-15 22:20 PST
Nmap scan report for 192.168.1.1
Host is up (0.00025s latency).
MAC Address: ZZ:ZZ:11:ZZ:ZZ:ZZ (Cisco-Linksys)
Nmap scan report for 192.168.1.2
Host is up (0.0084s latency).
MAC Address: ZZ:ZZ:A1:2E:ZZ:ZZ (Apple)
Nmap scan report for 192.168.1.9
Host is up (0.012s latency).
MAC Address: A4:ZZ:57:17:ZZ:ZZ (Seiko Epson)
Nmap scan report for 192.168.1.103
Host is up (0.036s latency).
MAC Address: ZZ:ZZ:6D:05:ZZ:ZZ (Apple)

I know that I can put together a regular expression to give me the IP address directly above the "Seiko Epson" line, but I cannot figure out how to do it. 我知道我可以将一个正则表达式组合在一起,以便在“ Seiko Epson”行上方直接给我IP地址,但是我不知道该怎么做。

I'm specifically looking for a way to find the IP address of the host that I'm searching for, I'm currently using: 我正在特别寻找一种寻找正在寻找的主机IP地址的方法,我目前正在使用:

(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)

to find IP addresses, but I do not know how to augment this to find the IP address above a given string. 查找IP地址,但是我不知道如何扩展它以查找给定字符串上方的IP地址。

If you get the whole input as a single string, then 如果您将整个输入作为单个字符串获取,则

  1. You firstly search for a fixed string Nmap scan report for , 首先,您要搜索固定字符串Nmap scan report for
  2. nextly remember a sequence 0-9 or . 接下来,请记住序列0-9. (which should be there) as the output IP address, (应该在此处)作为输出IP地址,
  3. then skip until the MAC addr part (containing : ), 然后跳过直到MAC地址部分(含有: ),
  4. skip until the next opening paren, 跳过直到下一个打开的paren,
  5. and finally check if the string inside parens is Seiko Epson . 最后检查parens中的字符串是否为Seiko Epson

Example: 例:

>>> inp='''Starting Nmap 6.40 ( http://nmap.org ) at 2014-02-15 22:20 PST
... Nmap scan report for 192.168.1.1
... Host is up (0.00025s latency).
... MAC Address: ZZ:ZZ:11:ZZ:ZZ:ZZ (Cisco-Linksys)
... Nmap scan report for 192.168.1.2
... Host is up (0.0084s latency).
... MAC Address: ZZ:ZZ:A1:2E:ZZ:ZZ (Apple)
... Nmap scan report for 192.168.1.9
... Host is up (0.012s latency).
... MAC Address: A4:ZZ:57:17:ZZ:ZZ (Seiko Epson)
... Nmap scan report for 192.168.1.103
... Host is up (0.036s latency).
... MAC Address: ZZ:ZZ:6D:05:ZZ:ZZ (Apple)'''
>>> import re
>>> r1 = re.compile(r'Nmap scan report for ([0-9.]*)[^:]*[^(]*\(Seiko Epson\)')
>>> r1.search(inp).group(1)
'192.168.1.9'

The idea behind [^ ... ] 's is finite state machine. [^ ... ]背后的思想是有限状态机。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM