Last active
January 30, 2019 21:00
-
-
Save tg12/be175bb8b608a25d35ba16eb4b63f97a to your computer and use it in GitHub Desktop.
Start of a lovely script to create iptables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import re | |
import socket, struct | |
from ipwhois import IPWhois | |
from ipaddress import ip_network, ip_address | |
ips = [] | |
with open("merged-file3") as f: | |
for line in f: | |
try: | |
line = line.rstrip('\n') | |
socket.inet_aton(line) | |
ips.append(str(line)) | |
except socket.error: | |
pass | |
print (ips) | |
cidr_ranges = [] | |
tmp_lst = [] | |
for ip in ips: | |
try: | |
b_found = False | |
for each in cidr_ranges: | |
net = ip_network(str(each)) | |
if ip_address(ip) in net: | |
print ("debug, already in list no call to WHOIS needed..." + str(ip)) | |
b_found = True | |
if b_found == False: | |
print ("debug, call to WHOIS needed, New range..." + str(ip)) | |
tmp_lst = [] | |
obj = IPWhois(ip) | |
out = obj.lookup_rdap() | |
print (out['network']['cidr']) | |
tmp_lst = out['network']['cidr'].split(', ') #deals with multiple ranges | |
# print (tmp_lst) | |
cidr_ranges.extend(tmp_lst) | |
except Exception as e: | |
print(e) | |
pass | |
cidr_ranges_dist = [] | |
for i in cidr_ranges: | |
if i not in cidr_ranges: | |
cidr_ranges_dist.append(i) | |
for cidr_range in cidr_ranges_dist: | |
print(cidr_range) | |
with open('cidr_ranges.txt', 'w') as f: | |
for item in cidr_ranges_dist: | |
f.write("%s\n" % item) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment