我有两个IP列表。我想验证每个对是否都存在于文件ips_template.txt
的同一行中。如果文件ips_template.txt
中不存在IP或它们不是“对”,请打印不匹配项。在bash
中,我将仅用管道输送两个grep
,以寻找具有相同结果的东西。
firstIPs = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", firststring)
secondIPs = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", secondstring)
if firstIPs or secondIPs :
print 'one of the lists didn\'t had IPs.'
sys.exit(2)
if len(firstIPs ) != len(secondIPs ):
print 'IPs len mismatch'
sys.exit(2)
for old, new in zip(firstIPs , secondIPs ):
# bash example to search in the file ips_template.txt
# if [ `cat ips_template.txt | grep old | grep new | wc -l` -gt 0 ]
# echo 'match'
# else
# echo ips not matched or missing
# fi
ips_template.txt
范例:
hostname 1.1.1.1 2.2.2.2 hostname_type
hostname2 1.1.1.1 2.2.2.2 hostname_type2
firststring
和secondstring
每次运行可以使用不同的格式,有些未知。这就是为什么我在假定IP /主机顺序相同的前提下仅从IP中删除IP的原因。
答案 0 :(得分:0)
要搜索ips_template.txt
的IP,我做了以下工作:
with open("ips_template.txt", "r") as ips_template_file:
ips_template = ips_template_file.readlines()
for old, new in zip(firstIPs , secondIPs ):
missing = True
pattern = r"%s\s*%s" % (old, new)
for line in ips_template:
if re.search(pattern, line):
print("matched %s %s" % (old, new))
missing = False
break
if missing:
print("missing %s %s" % (old, new))
另外,当检查列表中是否甚至包含IP时,我插入了两个not
:
if not firstIPs or not secondIPs:
因为它只说“其中一个列表没有IP”。当其中至少有一个包含IP时。
我处理过的完整代码是:
import re
import sys
firststring = "1.1.1.1\n1.1.1.1\n3.3.3.3\n2.2.2.2"
secondstring = "1.1.1.1\n2.2.2.2\n not an IP adress\n2.2.2.2\n4.4.4.4"
firstIPs = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", firststring)
secondIPs = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", secondstring)
if not firstIPs or not secondIPs :
print('one of the lists didn\'t had IPs.')
sys.exit(2)
if len(firstIPs ) != len(secondIPs ):
print('IPs len mismatch')
sys.exit(2)
with open("ips_template.txt", "r") as ips_template_file:
ips_template = ips_template_file.readlines()
for old, new in zip(firstIPs , secondIPs ):
missing = True
pattern = r"%s\s*%s" % (old, new)
for line in ips_template:
if re.search(pattern, line):
print("matched %s %s" % (old, new))
missing = False
break
if missing:
print("missing %s %s" % (old, new))
ips_template.txt
看起来像这样:
hostname 1.1.1.1 1.1.1.1 hostname_type
hostname2 3.3.3.3 2.2.2.2 hostname_type2
hostname3 2.2.2.2 2.2.2.2 hostname_type3
我的代码输出为:
matched 1.1.1.1 1.1.1.1
missing 1.1.1.1 2.2.2.2
matched 3.3.3.3 2.2.2.2
missing 2.2.2.2 4.4.4.4