-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathdns-a
More file actions
executable file
·155 lines (129 loc) · 4.83 KB
/
dns-a
File metadata and controls
executable file
·155 lines (129 loc) · 4.83 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
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#!/usr/bin/env python3
###########
# IMPORTS #
###########
import sys
import argparse
import asyncio
import aiodns
###########
# CLASSES #
###########
# TaskPool class taken from https://github.com/cgarciae/pypeln/blob/0.3.3/pypeln/task/utils.py
class TaskPool(object):
def __init__(self, workers):
self.semaphore = asyncio.Semaphore(workers) if workers else None
self.tasks = set()
self.closed = False
async def put(self, coro):
if self.closed:
raise RuntimeError("Trying put items into a closed TaskPool")
if self.semaphore:
await self.semaphore.acquire()
task = asyncio.create_task(coro)
self.tasks.add(task)
task.add_done_callback(self.on_task_done)
task.set_exception
def on_task_done(self, task):
task
self.tasks.remove(task)
if self.semaphore:
self.semaphore.release()
async def join(self):
await asyncio.gather(*self.tasks)
self.closed = True
async def __aenter__(self):
return self
def __aexit__(self, exc_type, exc, tb):
return self.join()
#############
# FUNCTIONS #
#############
async def fetch(name, resolver, addresses):
try:
results = await resolver.query(name, 'A')
for a in results:
if addresses is None or a.host in addresses:
sys.stdout.write('%s,%s\n' % (a.host, name))
sys.stdout.flush()
except Exception as e:
try:
err_number = e.args[0]
err_text = e.args[1]
except IndexError:
sys.stderr.write(f"{name} => Couldn't parse exception: {e}\n")
else:
if err_number == 4:
#sys.stderr.write(f"{address} => No record found.\n")
pass
elif err_number == 12:
# Timeout from DNS server
sys.stderr.write(f"{name} => Request timed out.\n")
elif err_number == 1:
# Server answered with no data
pass
else:
sys.stderr.write(f"{name} => Unexpected exception: {e}\n")
async def run(loop, limit, hostnames, addresses):
resolver = aiodns.DNSResolver(loop=loop, rotate=True)
async with TaskPool(limit) as tasks:
for name in hostnames:
await tasks.put(fetch(name, resolver, addresses))
########
# MAIN #
########
if __name__ == '__main__':
desc = 'Perform DNS lookup on supplied hostnames and output results in CSV format.'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('-n', '--nameservers',
nargs='?',
type=argparse.FileType('r'),
action='store',
help='file containing a list of nameservers split by a newline, otherwise use system resolver',
metavar='FILE',
default=None)
parser.add_argument('-f', '--filter',
nargs='?',
type=argparse.FileType('r'),
action='store',
help='a list of IP addresses to filter against, only matching results are printed',
metavar='FILE',
default=None)
parser.add_argument('file',
nargs='?',
type=argparse.FileType('r'),
action='store',
help='file containing a list of hostnames split by a newline, otherwise read from STDIN',
metavar='FILE',
default=sys.stdin)
parser.add_argument('-l', '--limit',
type=int,
action='store',
help='maximum number of queries to run asynchronosly (default: 100)',
metavar='INT',
default=100)
args = parser.parse_args()
if args.filter:
addresses = [line.strip() for line in args.filter if len(line.strip())>0 and line[0] != '#']
else:
addresses = None
try:
hostnames = [line.strip() for line in args.file if len(line.strip())>0 and line[0] != '#']
except KeyboardInterrupt:
exit()
# remove duplicates and sort
hostnames = sorted(set(hostnames))
if args.nameservers:
try:
nameservers = [line.strip() for line in args.nameservers if len(line.strip())>0 and line[0] != '#']
except KeyboardInterrupt:
exit()
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(run(loop, args.limit, hostnames, addresses))
except KeyboardInterrupt:
sys.stderr.write("\nCaught keyboard interrupt, cleaning up...\n")
asyncio.gather(*asyncio.Task.all_tasks()).cancel()
loop.stop()
finally:
loop.close()