从CIDR中查找IP

时间:2016-08-11 22:29:26

标签: python

我正在搜索s1中列出的CIDR中s2中列出的IP。所以基本上,我想扩展s2的所有元素并搜索IP。如果使用s1,请不要确定如何从re.compile获取IP。我没有得到ip4:,如何删除ip4:part

import re

s1 = ["ip4:64.18.10.101", "ip4:66.102.10.10", "spf1", "mx"]
s2 = "v=spf1 ip4:64.18.0.0/20 ip4:66.102.0.0/20 ~all"

list = s2.split(' ')
regex = re.compile("ip.*")
for ip in list:
    if re.search(regex, ip):
        print ip

1 个答案:

答案 0 :(得分:0)

最后我写了这个:

#/usr/bin/python
import os
import re
from netaddr import IPNetwork
import subprocess
import shlex

cmd = '/usr/bin/dig +short -t TXT _netblocks.google.com'
proc=subprocess.Popen(shlex.split(cmd),stdout=subprocess.PIPE)
s1,err=proc.communicate()

cmd3 = '/usr/bin/dig +short -t TXT _netblocks3.google.com'
proc=subprocess.Popen(shlex.split(cmd3),stdout=subprocess.PIPE)
s3,err=proc.communicate()

s2 = ''.join([s1,s3])
regex = re.compile("\d+\.\d+\.\d+\.\d+\/[0-9][0-9]")
list = re.findall(regex, s2)
f2 = open("s1.txt", "w")
for ip in list:
    for ip1 in IPNetwork(ip):
        #print ip1
        f2.write(str(ip1)+'\n')


#######################
f = open("/var/log/iptables.log")
f1 = open("s_out.txt", "w")
pattern = re.compile(r"\bSRC\=\d+\.\d+\.\d+\.\d+")
for line in f:
    test = re.findall(pattern,line)
    for line in test:
        line1 = re.split("=", line)
        f1.write(line1[1]+'\n')
f1.close()


#######################
with open('s_out.txt', 'r')as f1:
    with open('s1.txt', 'r') as f2:
        same = set(f1).intersection(f2)
same.discard('\n')

with open('outfile.txt', 'w') as file_out:
    for line in same:
        file_out.write(line)

uniqlines = set(open('outfile.txt').readlines())
bar = open('output_file.txt', 'w').writelines(set(uniqlines))