0

我正在尝试过滤谷歌电子表格中的一堆乱码,然后只提取 IP 地址并存储它们,以便以后进行比较。IE用户输入

"Summary: unauthorized ms-rdp traffic
Notes:  SRC_IP: 211.238.202.137   91.212.144.2   92.66.145.194   121.229.128.42   81.162.195.34   81.88.125.86    213.42.28.188   85.21.42.240   94.56.89.117   177.55.40.14   219.69.14.40
SRC_Port:
SRC_Country: US KR IL CN CZ AE RU BR TW
DST_IP: MANY
DST_Port:
DST_Country: US
Campus_Agency:"

该脚本存储所有 scr_ip 地址,以后如果需要,用户可以输入一个 IP 地址,如 211.238.202.137,它将返回一个验证 IP 是否在列表中的语句。我已经尝试过 if 语句并且没有运气,我一直在尝试不同的变化,我认为这只是我的技能集。我最接近的是它提取了 IP 地址,但按值对它们进行了排序,因此它们与原件不匹配

4

2 回答 2

2

一个快速的正则表达式,可以提取所有类似 IP 地址的文本:

import re

ipaddress = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')

addresses = ipaddress.findall(inputtext)
if '211.238.202.137' in addresses:
    print 'We have a match!'

对于您的示例文本,.findall()调用返回:

>>> ipaddress.findall(inputtext)
['211.238.202.137', '91.212.144.2', '92.66.145.194', '121.229.128.42', '81.162.195.34', '81.88.125.86', '213.42.28.188', '85.21.42.240', '94.56.89.117', '177.55.40.14', '219.69.14.40']
于 2013-04-09T12:59:09.540 回答
0
import re

text = """Summary: unauthorized ms-rdp traffic
Notes:  SRC_IP: 211.238.202.137   91.212.144.2   92.66.145.194   121.229.128.42   81.162.195.34   81.88.125.86    213.42.28.188   85.21.42.240   94.56.89.117   177.55.40.14   219.69.14.40
SRC_Port:
SRC_Country: US KR IL CN CZ AE RU BR TW
DST_IP: MANY
DST_Port:
DST_Country: US
Campus_Agency:"""

"""This will store all the ips in the text variable in a list called ips"""
ips = re.findall('(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', text, re.DOTALL)

ipEntered = raw_input('Please enter an IP: ')
if ipEntered in ips:
    print 'The IP you entered is in the list.'
else:
    print 'The IP you entered is not in the list.'
于 2013-04-09T13:00:01.183 回答