Last active
April 26, 2017 12:41
-
-
Save VGostyuzhov/447d0735cd424f766bd083a2db1ee8e8 to your computer and use it in GitHub Desktop.
Query Whois for each IP from file, get info about Netwrok for that IP and saves it into CSV file. Requirements: pip install ipwhois, argparse
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/python | |
from ipwhois import IPWhois | |
import sys | |
import csv | |
from argparse import ArgumentParser | |
def whois_query_ip(ip): | |
whois_nets = [] | |
try: | |
query = IPWhois(ip) | |
res = query.lookup_whois() | |
for net in res['nets']: | |
whois_net = {} | |
try: | |
whois_net['CIDR'] = net['cidr'] | |
except: | |
pass | |
try: | |
whois_net['Country'] = net['country'] | |
except: | |
pass | |
try: | |
whois_net['Description'] = net['description'].replace('\n', ' ') | |
except: | |
pass | |
try: | |
whois_net['Address'] = net['address'].replace('\n', ' ') | |
except: | |
pass | |
try: | |
whois_net['Name'] = net['name'] | |
except: | |
pass | |
try: | |
whois_net['Range'] = net['range'] | |
except: | |
pass | |
try: | |
whois_net['ASN'] = res['asn'] | |
except: | |
pass | |
try: | |
whois_net['Emails'] = ' '.join(net['emails']).replace('\n', ' ') | |
except: | |
pass | |
whois_nets.append(whois_net) | |
except: | |
pass | |
return whois_nets | |
def whois_get_net(ip_list, csvwriter): | |
whois_nets = [] | |
for ip in ip_list: | |
for whois_net in whois_query_ip(ip): | |
if whois_net not in whois_nets: | |
whois_nets.append(whois_net) | |
csvwriter.writerow(whois_net) | |
def main(): | |
parser = ArgumentParser(description='Query Whois for each IP from file, get info about Netwrok for that IP and saves it into CSV file') | |
parser.add_argument('-f', dest='source_file', help='Enter filename, containing list of IPs', metavar='FILE') | |
if len(sys.argv) == 1: | |
parser.print_help() | |
sys.exit(1) | |
args = parser.parse_args() | |
with open(args.source_file, 'r') as file, open('whois_result.csv', 'wb') as csvfile: | |
csvfields = ['Description', 'Name','Address', 'ASN', 'CIDR', 'Country', 'Emails', 'Range'] | |
csvwriter = csv.DictWriter(csvfile, csvfields, restval='None', delimiter=';') | |
csvwriter.writeheader() | |
ip_list = file.readlines() | |
ip_list = [ip.strip() for ip in ip_list] | |
whois_get_net(ip_list, csvwriter) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment