Skip to content

Instantly share code, notes, and snippets.

@cutaway
Created October 16, 2018 15:39
Show Gist options
  • Save cutaway/955f8f8bded17e7da2af79865437517f to your computer and use it in GitHub Desktop.
Save cutaway/955f8f8bded17e7da2af79865437517f to your computer and use it in GitHub Desktop.
ARIN Lookup for IP Ranges
import os,sys
from ipwhois import IPWhois
import socket
import warnings
# Supress warnings
warnings.filterwarnings('ignore')
# Set field names
f = ['asn','asn_cidr','nets','query','asn_description']
# Set field names for nets
n = ['cidr','description','name']
def get_urlwhois(in_url):
value = ""
tmp = []
# Add query value to first field
try:
in_ip = socket.gethostbyname(in_url.rstrip())
except:
# There was a problem resolving the URL
return None
tmp = get_ipwhois(in_ip)
# Test to see if there was a problem
if tmp:
tmp[0] = in_url.rstrip() + ":" + tmp[0]
return tmp
def get_ipwhois(in_ip):
tmp = []
# Add query value to first field
tmp.append(in_ip.rstrip())
try:
d = IPWhois(in_ip.rstrip()).lookup_whois()
except:
# There was a problem checking the IP address (RFC 1918?).
return None
for e in f:
value = ""
# Check for 'nets' and process sub-fields
if e == 'nets':
for g in n:
value = ""
#tmp.append(d[e][0][g].replace(',',''))
# Some fields are empty, test them
try:
value = d[e][0][g]
if value:
# Clear out any commas
value = value.replace(',','').replace('\n',':')
else:
value = '.'
except:
value = '.'
tmp.append(value)
else:
#tmp.append(d[e].replace(',',''))
# Some fields are empty, test them
value = d[e]
if value:
# Clear out any commas
value = value.replace(',','').replace('\n',':')
else:
value = '.'
tmp.append(value)
return tmp
if __name__ == "__main__":
ops = ['-h','-f','-o','-u']
cnt = 0
TYPE = 'ip'
while len(sys.argv) > 1:
op = sys.argv.pop(1)
if op == '-h':
usage()
if op == '-f':
inf = sys.argv.pop(1)
if inf == "-":
print sys.argv[0] + ": STDIN Not Implemented Yet"
sys.exit()
# Implement for future usage
inf = sys.stdin
STDIN = True
if op == '-o':
onf = sys.argv.pop(1)
ONF = open(onf,'w')
if op == '-u':
TYPE = 'url'
# Generate and Print Header in the other that it will be processed and output
header = []
header.append('Query Value')
for e in f:
if e == 'nets':
for g in n:
header.append(g)
else:
header.append(e)
# print header
print ','.join(header)
# Open file for IP addresses
#inf = 'ip_addrs.txt'
r = open(inf,'r').readlines()
# Process file
if TYPE == 'ip':
for i in r:
query_info = get_ipwhois(i)
# Print to Stdout
if query_info:
print ','.join(query_info)
if TYPE == 'url':
for i in r:
query_info = get_urlwhois(i)
# Print to Stdout
if query_info:
print ','.join(query_info)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment