Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- """ whereip
- use curl to get location of ip
- """
- #-----------------------------------------
- __author__ = "Chris Reid"
- __category__ = "network utility"
- __copyright__ = "Copyright 2016"
- __country__ = "United States of America"
- __credits__ = ["Python Software Foundation", "Free Software Foundation" ]
- __email__ = "spikeysnack@gmail.com"
- __file__ = ["whereip", "whereip.py"]
- __license__ = """Free for all non-commercial purposes.
- Modifications allowed but original attribution must be included.
- see (http://creativecommons.org/licenses/by-nc/4.0/)"""
- __maintainer__ = "chris Reid"
- __modification_date__ = "31 Oct 2016"
- __version__ = "1.1"
- __status__ = "beta"
- #-----------------------------------------
- #--------
- import os
- import sys
- import ast
- import subprocess
- URL = "ipinfo.io" # this is the service that returns the info
- #--------------------
- def ip_to_dict( ip ):
- """ get a series of strings from ipinfo.io
- and make a dictionary out of it
- Args:
- ip (str): the 4-dotted ip number
- Returns:
- ip_info (dict): a dictionary of location info
- {
- 'loc': '37.3860,-122.0838',
- 'city': 'Mountain View',
- 'country': 'US',
- 'region': 'California',
- 'hostname': 'google-public-dns-a.google.com',
- 'ip': '8.8.8.8',
- 'org': 'AS15169 Google Inc.',
- 'postal': '94035'
- }
- """
- l = ""
- command = "curl -s " + URL+ "/" + ip
- ip_info = {}
- p = subprocess.Popen( command , shell=True, stdout=subprocess.PIPE)
- """ class subprocess.Popen: run system process, capture output """
- retval = p.wait()
- """ int|None: Wait for child process to terminate, get returncode """
- # gather lines into one string
- for line in p.stdout.readlines():
- l = l + line
- ip_info = ast.literal_eval( l )
- ''' dict: eval string as python dict '''
- return ip_info
- # ip_to_dict
- #------------------
- #script starts here
- if __name__ == '__main__':
- IP = ""
- if len(sys.argv) > 1:
- IP=sys.argv[1]
- ipinfo = ip_to_dict( IP )
- # print (ipinfo)
- # for k in ipinfo:
- # print ( k + " = " + ipinfo[k] + "\n" )
- loc = ipinfo["loc"]
- city = ipinfo["city"]
- region = ipinfo["region"]
- country = ipinfo["country"]
- hostname = ipinfo["hostname"]
- print ( country + ':\t' + region + ':\t' + city + ':\t' + hostname + '\n' )
- #end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement