#!/usr/bin/python3
# Benjamyn Love
# 2018/2019
# bip (Bulk IP lookup)

import dns.resolver
import ipwhois
from dns import reversename
from ipwhois.net import Net
from ipwhois.asn import IPASN
import warnings

ipList = []

def loadBlacklist():
    with open('blacklist.txt') as handle:
        blacklist = handle.readlines()
    for i in range(len(blacklist)):
        blacklist[i] = blacklist[i].strip()
    return blacklist

def lookupIP(inData):
    try:
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", category=UserWarning)
            ipnet = Net(inData)
            ipobj = IPASN(ipnet)
            results = ipobj.lookup()
            # print(results)
            return results

    except ipwhois.exceptions.IPDefinedError:
        pass # We do not care about local/invalid IPs
    except Exception as e:
        pass # Garbage data was given lol


def parseIPS():
    global countIncluded
    with open("ips.txt", 'r') as f:
        ipData = f.read()

    data = ipData.split('\n')
    for ip in data:
        ip = ip.strip()
        ipAddr = ip.split()
        if len(ipAddr) == 2:
            countIncluded = True
            ipList.append(ipAddr)
        else:
            if len(ipAddr) == 0:
                pass
            else:
                countIncluded = False
                ipList.append(ipAddr)


blacklist = loadBlacklist()
parseIPS()

for ips in ipList:
    # ccode = ipCheck(lookupIP(ips[1]))
    if countIncluded == True:
        ret = lookupIP(ips[1])
        reverseName = reversename.from_address(ips[1])
    else:
        ret = lookupIP(ips[0])
        reverseName = reversename.from_address(ips[0])

    if ret == None:
        continue

    cc = ret["asn_country_code"]
    desc = ret["asn_description"]
    if cc in blacklist:
        continue
    
    try:
        ptr = str(dns.resolver.query(reverseName, "PTR")[0])
    except dns.resolver.NoAnswer as E:
        ptr = reverseName
    except dns.resolver.NoNameservers as E:
        ptr = reverseName
    except dns.resolver.NXDOMAIN as E:
        ptr = reverseName

    if countIncluded == True:
        print("IP: {}\t\tCountry: {}\tDesc: {}\tPTR: {}\tCount: {}".format(ips[1], cc, desc, ptr, ips[0]))
    else:
        print("IP: {}\t\tCountry: {}\tDesc: {}\tPTR: {}".format(ips[0], cc, desc, ptr))

