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

时间:2014-02-16 06:32:32

标签: python regex nmap

我正在使用nmap在我的本地(家庭)网络上搜索主机名和相关IP。我可以拉一个看起来像这样的字符串:

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)

我知道我可以把一个正则表达式放在一起,直接给我“精工爱普生”系列上面的IP地址,但我无法弄明白该怎么做。

我正在寻找一种方法来查找我正在搜索的主机的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]?)

找到IP地址,但我不知道如何扩充它以找到给定字符串上方的IP地址。

1 个答案:

答案 0 :(得分:1)

如果您将整个输入作为单个字符串,那么

  1. 您首先搜索固定字符串Nmap scan report for
  2. 接下来记住序列0-9.(应该在那里)作为输出IP地址,
  3. 然后跳到MAC地址部分(包含:),
  4. 跳到下一个开场白,
  5. 最后检查parens中的字符串是否为Seiko Epson
  6. 示例:

    >>> 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'
    

    [^ ... ]背后的想法是有限状态机。