-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathhosts_to_country
More file actions
executable file
·90 lines (75 loc) · 2.72 KB
/
hosts_to_country
File metadata and controls
executable file
·90 lines (75 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env python3
###########
# IMPORTS #
###########
import argparse
import sys
def iter_input_lines(handle):
for line in handle:
value = line.strip()
if value and not value.startswith('#'):
yield value
########
# MAIN #
########
if __name__ == '__main__':
desc = (
'Look up IPv4 or IPv6 addresses in a MaxMind GeoLite2 Country '
'database and print CSV rows as IP,COUNTRY,ISO_CODE.'
)
epilog = '''
Requirements:
- Install the Python package: pip3 install geoip2
- Download a MaxMind GeoLite2 Country database from:
https://dev.maxmind.com/geoip/geolite2-free-geolocation-data
- Pass the downloaded .mmdb path via --geolite.
Input:
- Read IP addresses from FILE or STDIN, one entry per line.
- Blank lines and lines starting with # are ignored.
Behavior:
- Each successful lookup prints CSV: IP,COUNTRY,ISO_CODE
- Failed lookups are written to stderr and do not stop the script.
Examples:
hosts_to_country -g GeoLite2-Country.mmdb ips.txt
cat ips.txt | hosts_to_country -g /path/to/GeoLite2-Country.mmdb
'''
parser = argparse.ArgumentParser(
description=desc,
epilog=epilog,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument('file',
nargs='?',
type=argparse.FileType('r'),
action='store',
help='file containing IP addresses split by newlines, otherwise read from STDIN',
metavar='FILE',
default=sys.stdin)
parser.add_argument('-g', '--geolite',
action='store',
help='path to MaxMind\'s GeoLite2 Country .mmdb database file; see https://dev.maxmind.com/geoip/geolite2-free-geolocation-data',
metavar='DB',
required=True)
args = parser.parse_args()
try:
import geoip2.database
except ModuleNotFoundError:
sys.stderr.write('Missing Python dependency: geoip2. Install it with: pip3 install geoip2\n')
sys.exit(1)
try:
reader = geoip2.database.Reader(args.geolite)
except OSError as exc:
sys.stderr.write(f'Unable to open GeoLite database {args.geolite}: {exc}\n')
sys.exit(1)
try:
addresses = [line for line in iter_input_lines(args.file)]
except KeyboardInterrupt:
exit()
for address in addresses:
try:
response = reader.country(address)
print(f"{address},{response.country.name},{response.country.iso_code}")
except Exception as e:
sys.stderr.write(f"[-] {address}: {e}\n")
sys.stderr.flush()
reader.close()