2013-04-09 89 views
0

我正试图通过google电子表格中的一堆jiberish文本进行过滤,并且只需将IP地址并将其存储起来,以便日后可以对其进行比较。 IE用户将在JavaScript或Python从块数据中提取IP地址

"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地址的和以后如果需要的话,用户可以输入如211.238.202.137的IP地址,它会返回一个验证IP的声明是在或者不在, 列表。我试过了,如果没有运气,我一直在尝试不同的变化,我认为这只是我的技能一点点。最近我来是很拽的IP地址,但它们排序按价值计算,因此他们没有符合原稿

+0

发布您的代码。 – dstronczak 2013-04-09 12:56:10

回答

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'] 
+1

123.456.789.876是一个有效的IP地址? – jarnbjo 2013-04-09 13:04:45

+1

@jarnbjo:它将所有* ip-address-like文本*取出。 :-)在Python 3.3中,我们可以使用'ipaddress'模块来验证它们。但是,是的,这是假定输入文本只包含实际在正确范围内的虚线四边形,但这不是一个巨大的飞跃。 – 2013-04-09 13:05:45

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