-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhosts.py
136 lines (94 loc) · 2.17 KB
/
hosts.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import asyncio
import functools
import socket
import json
import aiofiles
def gethostname(line):
(
address,
hostname
) = (
line
.split(sep = " ", maxsplit = 1)
)
host = hostname.strip()
return host
async def agetaddrinfo(host):
res = None
print("Checking for %s" % (host))
loop = asyncio.get_running_loop()
func = functools.partial(
socket.getaddrinfo,
host = host,
port = 80
)
try:
res = await loop.run_in_executor(None, func)
except socket.gaierror:
pass
print("res: %s" % str(res))
return (host, res)
async def main():
tasks = []
mapping = {}
finished = False
async with (
aiofiles.open(file = "./hosts", mode = "r") as file,
aiofiles.open(file = "./hosts2", mode = "w") as file2
):
iterable = aiter(file)
while True:
line = await anext(iterable)
host = gethostname(line = line)
task = asyncio.create_task(
coro = agetaddrinfo(host = host)
)
tasks.append(task)
if len(tasks) == 1024:
break
task_index = -1
total_tasks = (len(tasks) - 1)
while True:
task_index += 1
if task_index > total_tasks:
task_index -= task_index
await asyncio.sleep(0.1)
task = tasks[task_index]
if task is None:
if all(task is None for task in tasks):
break
continue
done = task.done()
if not done:
continue
result = task.result()
(host, addresses) = result
if addresses is not None:
text = ":: %s\n" % (host)
await file2.write(text)
occurrences = 0
for address in addresses:
ip = address[-1][0]
occurrences = mapping.get(ip)
if occurrences is None:
occurrences = 0
occurrences += 1
mapping.update(
{
ip: occurrences
}
)
line = None
try:
line = await anext(iterable)
except StopAsyncIteration:
finished = True
tasks[task_index] = None if finished else asyncio.create_task(
coro = agetaddrinfo(
host = gethostname(line = line)
)
)
text = json.dumps(obj = mapping)
async with aiofiles.open(file = "./mapping.json", mode = "w") as file:
await file.write(text)
asyncio.run(main())