forked from emphazer/mmutils
-
Notifications
You must be signed in to change notification settings - Fork 1
/
merge_geoip_csv
executable file
·63 lines (50 loc) · 1.65 KB
/
merge_geoip_csv
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
#!/usr/bin/env python
from argparse import ArgumentParser
import sys, os
from csv import reader, writer, Sniffer, QUOTE_ALL
from ipaddress import IPv6Address
arg_parser = ArgumentParser()
arg_parser.add_argument('-o', '--output', default=None,
help = 'Output to the specified file name (default is stdout)')
arg_parser.add_argument('ipv4_csv', help = 'Maxmind\'s GeoIP IPv4 country file to merge')
arg_parser.add_argument('ipv6_csv', help = 'Maxmind\'s GeoIP IPv6 country file to merge')
args = arg_parser.parse_args()
if args.output is None :
output = sys.stdout
else :
output = open(args.output, 'w')
ipv4_csv = open(args.ipv4_csv, 'r')
ipv6_csv = open(args.ipv6_csv, 'r')
# Sniff the format
dialect = Sniffer().sniff(ipv6_csv.read(1024))
ipv6_csv.seek(0)
output_csv = writer(output, dialect, quoting = QUOTE_ALL)
lsnat_ip = (
"0:0:0:0:0:ffff:100.64.0.1",
"0:0:0:0:0:ffff:100.127.255.254",
281472363659265,
281472367853566,
"TH",
"Thailand",
)
# For V4, we need to translate it to v6
lsnat_inserted = False
for row in reader(ipv4_csv, dialect) :
v6_start = '0:0:0:0:0:ffff:' + row[0]
v6_start_int = int(IPv6Address(unicode(v6_start)))
v6_end = '0:0:0:0:0:ffff:' + row[1]
v6_end_int = int(IPv6Address(unicode(v6_end)))
if not lsnat_inserted and (v6_start_int > lsnat_ip[2]) :
output_csv.writerow(lsnat_ip)
lsnat_inserted = True
output_csv.writerow([
v6_start, v6_end,
v6_start_int, v6_end_int,
row[4], row[5],
])
for row in reader(ipv6_csv, dialect) :
output_csv.writerow(row)
ipv4_csv.close()
ipv6_csv.close()
if not args.output is None :
output.close()