Monday, October 8, 2018

(Python) GeoLocation of an IP address from the command line.



import sys
import json
import urllib.request

url = "http://ipinfo.io/" + sys.argv[1] + "/json"

#print(url)
with urllib.request.urlopen(url) as response:
    myDict = json.loads(response.read().decode())

try:
    outputHostname  = 'Hostname:\t{}\n'.format(myDict.get("hostname"))
    outputCity      = 'City:\t\t{}\n'.format(myDict.get("city"))
    outputRegion    = 'Region:\t\t{}\n'.format(myDict.get("region"))
    outputCountry   = 'Country:\t{}\n'.format(myDict.get("country"))
    outputLoc       = 'Loc:\t\t{}\n'.format(myDict.get("loc"))
    outputPostal    = 'Postal:\t\t{}\n'.format(myDict.get("postal"))
    outputPhone     = 'Phone:\t\t{}\n'.format(myDict.get("phone"))
    outputOrg       = 'Org:\t\t{}'.format(myDict.get("org"))

    output =  outputHostname + outputCity + outputRegion + outputCountry + outputLoc + outputPostal + outputPhone + outputOrg                             
    print(output)
except:
    output = 'IP Address: {}\nBogon: {}'.format(myDict.get('ip'),myDict.get('bogon'))
    print(output)