-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathdns-ptr
More file actions
executable file
·143 lines (117 loc) · 4.28 KB
/
dns-ptr
File metadata and controls
executable file
·143 lines (117 loc) · 4.28 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
#!/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(address, resolver):
try:
result = await resolver.gethostbyaddr(address)
for host in result.aliases:
sys.stdout.write('%s,%s\n' % (address, host))
sys.stdout.flush()
except Exception as e:
try:
err_number = e.args[0]
err_text = e.args[1]
except IndexError:
sys.stderr.write(f"{address} => 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"{address} => Request timed out.\n")
elif err_number == 1:
# Server answered with no data
pass
else:
sys.stderr.write(f"{address} => Unexpected exception: {e}\n")
async def run(loop, limit, addresses):
resolver = aiodns.DNSResolver(loop=loop, rotate=True)
async with TaskPool(limit) as tasks:
for address in addresses:
await tasks.put(fetch(address, resolver))
########
# MAIN #
########
if __name__ == '__main__':
desc = 'Perform reverse DNS lookup on supplied IP addresses 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('file',
nargs='?',
type=argparse.FileType('r'),
action='store',
help='file containing a list of IP addresses 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()
try:
addresses = [line.strip() for line in args.file if len(line.strip())>0 and line[0] != '#']
except KeyboardInterrupt:
exit()
# remove duplicates and sort results
addresses = sorted(set(addresses))
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, addresses))
except KeyboardInterrupt:
sys.stderr.write("\nCaught keyboard interrupt, cleaning up...\n")
asyncio.gather(*asyncio.Task.all_tasks()).cancel()
loop.stop()
finally:
loop.close()