下面的代码将…
- 即使经过审查也可以找到字符串中的IP(例如:192.168.1 [20]或10.10.10 .21)
- 将它们放入列表
- 清除检查内容(空格/花括号/括号)
- 并将未清除的列表条目替换为已清除的列表条目。
注意:
以下代码不能解释不正确/无效的IP,例如192.168.0.256或192.168.1.2.3。当前,它将删除尾随数字(上述数字为6和3)。如果其第一个八位位组无效(例如:256.10.10.10),它将删除前导数字(结果为56.10.10.10)。
import redef extractIPs(fileContent): pattern = r"((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)([ ([]?(.|dot)[ )]]?(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})" ips = [each[0] for each in re.findall(pattern, fileContent)] for item in ips: location = ips.index(item) ip = re.sub("[ ()[]]", "", item) ip = re.sub("dot", ".", ip) ips.remove(item) ips.insert(location, ip) return ipsmyFile = open('***INSERT FILE PATH HERE***')fileContent = myFile.read()IPs = extractIPs(fileContent)print "Original file content:n{0}".format(fileContent)print "--------------------------------"print "Parsed results:n{0}".format(IPs)`



