|
| 1 | + |
| 2 | +# ipapi Python bindings (https://ipapi.co) |
| 3 | +# API docs at https://ipapi.co/api |
| 4 | + |
| 5 | +import sys |
| 6 | +import argparse |
| 7 | +from requests import get |
| 8 | + |
| 9 | +headers = {'user-agent': 'ipapi/ipapi-python/0.4'} |
| 10 | +API_KEY = '' |
| 11 | + |
| 12 | + |
| 13 | +def location(ip=None, key=None): |
| 14 | + ''' Get complete geolocation data (as JSON) for given IP address ''' |
| 15 | + if ip: |
| 16 | + url = 'https://ipapi.co/{}/json/'.format(ip) |
| 17 | + else: |
| 18 | + url = 'https://ipapi.co/json/' |
| 19 | + if key or API_KEY: |
| 20 | + url = '{}?key={}'.format(url, (key or API_KEY)) |
| 21 | + |
| 22 | + response = get(url, headers=headers) |
| 23 | + return response.json() |
| 24 | + |
| 25 | + |
| 26 | +def field(field, ip=None, key=None): |
| 27 | + ''' Get specific geolocation field (as text) for given IP address ''' |
| 28 | + if ip: |
| 29 | + url = 'https://ipapi.co/{}/{}/'.format(ip, field) |
| 30 | + else: |
| 31 | + url = 'https://ipapi.co/{}/'.format(field) |
| 32 | + if key or API_KEY: |
| 33 | + url = '{}?key={}'.format(url, (key or API_KEY)) |
| 34 | + |
| 35 | + response = get(url, headers=headers) |
| 36 | + return response.text |
| 37 | + |
| 38 | + |
| 39 | +def main(argv=None): |
| 40 | + field_list = ['ip', 'city', 'region', 'country', 'postal', 'latitude', 'longitude', 'timezone', 'latlong'] |
| 41 | + |
| 42 | + argv = argv or sys.argv[1:] |
| 43 | + parser = argparse.ArgumentParser(description='IP address location API : https://ipapi.co') |
| 44 | + parser.add_argument('-i', '--ip', dest='ip', help='IP address') |
| 45 | + parser.add_argument('-f', '--field', dest='field', help='specific field e.g. {}'.format(', '.join(field_list)), default=None) |
| 46 | + parser.add_argument('-k', '--key', dest='key', help='API key', default=None) |
| 47 | + args = parser.parse_args(argv) |
| 48 | + |
| 49 | + if args.field and (args.field not in field_list): |
| 50 | + print 'Invalid field : {}'.format(args.field) |
| 51 | + return |
| 52 | + |
| 53 | + if args.field: |
| 54 | + print field(args.field, args.ip, args.key) |
| 55 | + else: |
| 56 | + print location(args.ip, args.key) |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == "__main__": |
| 60 | + sys.exit(main()) |
0 commit comments