-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharchive_to_ips.py
executable file
·91 lines (73 loc) · 2.23 KB
/
archive_to_ips.py
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
91
#!/usr/bin/env python3
import argparse
import ipaddress
import logging
import multiprocessing
import re
import sys
import zipfile
EXPRESSION = re.compile(".*dump.*\.csv")
LOGGER = logging.getLogger("archive_to_ips")
parser = argparse.ArgumentParser(description="Extract IPs from zapret-info archive")
parser.add_argument(
"archive", type=argparse.FileType("rb"), default=sys.stdin, help="Source archive"
)
parser.add_argument(
"--output",
"-o",
type=argparse.FileType("w"),
default=sys.stdout,
help="Output file (default = stdout)",
)
parser.add_argument(
"--processes",
type=int,
default=multiprocessing.cpu_count(),
help="Number of parser threads (default = cpu count)",
)
parser.add_argument(
"--chunksize", type=int, default=128, help="Parser chunksize (default = 128)"
)
parser.add_argument(
"--loglevel",
type=str,
default="INFO",
choices=("CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "NOTSET"),
)
args = parser.parse_args()
logging.basicConfig(level=args.loglevel.upper())
dest = args.output
def file_iterator():
archive = zipfile.ZipFile(args.archive)
for filename in archive.namelist():
if EXPRESSION.match(filename):
LOGGER.debug("Processing file %s", filename)
with archive.open(filename, "r") as src:
yield from src
def handle_line(line):
line = line.decode("cp1251")
if ";" not in line:
return []
ip_entries, _ = line.split(";", 1)
line_ips = []
for entry in ip_entries.split("|"):
entry = entry.strip()
try:
address = ipaddress.ip_address(entry)
if address.version == 4:
line_ips.append(address)
except ValueError:
try:
network = ipaddress.ip_network(entry)
if network.version == 4:
line_ips.extend(network.hosts())
except ValueError:
continue
return line_ips
ips = set()
pool = multiprocessing.Pool(processes=args.processes)
for line_ips in pool.imap_unordered(handle_line, file_iterator(), args.chunksize):
for address in line_ips:
if address not in ips:
ips.add(address)
dest.write(str(address) + "\n")