This repository has been archived by the owner on Aug 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnmappoll
executable file
·243 lines (227 loc) · 10.1 KB
/
nmappoll
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#!/usr/bin/env python
# Copyright (c) 2018 James P. Harmison
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import sys
from datetime import datetime, timedelta
from time import sleep
try:
from libnmap.process import NmapProcess
from libnmap.parser import NmapParser, NmapParserException
except:
sys.stderr.write('You need libnmap to use this file.\n`pip install python-libnmap` or source your virtualenv.\n')
sys.stderr.flush()
exit(1)
# doScan conducts a scan on [targets] with [options] and returns a tuple
# of the NmapParser object and stdout from the process.
def doScan(targets, options):
parsed= None
nmproc = NmapProcess(targets, options)
# Will ask for sudoer password if not root already, but will continue
# to do this if your scans take longer than the 15 minutes or
# whatever your sudoers cache is set to.
nmproc.sudo_run_background()
# Status display throughout scan
while nmproc.is_running():
# The time remaining goes a bit crazy if it hits negative, so we
# just set it to 1 second if nmap has (apparently) no idea how
# much longer it'll take.
if datetime.fromtimestamp(float(nmproc.etc)) > datetime.now():
timeRemaining=str(datetime.fromtimestamp(float(nmproc.etc)) - datetime.now()).split('.',2)[0]
else:
timeRemaining=str(timedelta(seconds=1))
# Fixed length progress bar with percentage and time estimate
progbar="\rNmap status: ["
progbar+='=' * (int(float(nmproc.progress)) / 2)
progbar+=' ' * (50 - (int(float(nmproc.progress)) / 2))
progbar+='] {0: >3}% (ETA: {1})'.format(nmproc.progress, timeRemaining)
progbar+=' ' * (120 - len(progbar))
sys.stdout.write(progbar)
sys.stdout.flush()
sleep(1)
# When it finishes, sometimes it says 0% or 99%, so let's just clean
# that up
finalOut='\rNmap status: [' + '=' * 50 + '] 100% (ETA: Done)'
sys.stdout.write(finalOut + ' ' * (120-len(finalOut)))
sys.stdout.flush()
# Error handling
if nmproc.rc != 0:
sys.stderr.write("nmap scan failed: {0}".format(nmproc.stderr))
return (None, None)
# Try to parse it
try:
parsed = NmapParser.parse(nmproc.stdout)
except NmapParserException as e:
sys.stderr.write("Exception raised while parsing scan: {0}".format(e.msg))
return (None, None)
return (parsed, nmproc.stdout)
# Produces a moderately useful, extremely compact, output of the things
# that probably matter to you (at least the ones that matter to me)
# from a parsed Nmap scan.
def prettyOutput(nmapParsed):
print nmapParsed.summary
for host in nmapParsed.hosts:
print host.address
for hostname in host.hostnames:
print ' ', hostname
for os in host.os.osmatches:
print ' {0} - {1}'.format(os.name, os.accuracy) + "%"
for port in host.get_open_ports():
service=host.get_service(port[0],port[1])
portline='\t{0: >5}/{1} {2: <18}'.format(port[0],port[1],service.service)
if service.banner:
portline+=service.banner
print portline
# All of the following functions serve to make the diffs work easily,
# but they were lifted straight from the libnmap documentation (under
# CC) - https://libnmap.readthedocs.io/en/latest/
# This wheel worked fine, no need to re-invent here.
def nested_obj(objname):
rval = None
splitted = objname.split("::")
if len(splitted) == 2:
rval = splitted
return rval
def print_diff_added(obj1, obj2, added):
for akey in added:
nested = nested_obj(akey)
if nested is not None:
if nested[0] == 'NmapHost':
subobj1 = obj1.get_host_byid(nested[1])
elif nested[0] == 'NmapService':
subobj1 = obj1.get_service_byid(nested[1])
print("+ {0}".format(subobj1))
else:
print("+ {0} {1}: {2}".format(obj1, akey, getattr(obj1, akey)))
def print_diff_removed(obj1, obj2, removed):
for rkey in removed:
nested = nested_obj(rkey)
if nested is not None:
if nested[0] == 'NmapHost':
subobj2 = obj2.get_host_byid(nested[1])
elif nested[0] == 'NmapService':
subobj2 = obj2.get_service_byid(nested[1])
print("- {0}".format(subobj2))
else:
print("- {0} {1}: {2}".format(obj2, rkey, getattr(obj2, rkey)))
def print_diff_changed(obj1, obj2, changes):
for mkey in changes:
nested = nested_obj(mkey)
if nested is not None:
if nested[0] == 'NmapHost':
subobj1 = obj1.get_host_byid(nested[1])
subobj2 = obj2.get_host_byid(nested[1])
elif nested[0] == 'NmapService':
subobj1 = obj1.get_service_byid(nested[1])
subobj2 = obj2.get_service_byid(nested[1])
print_diff(subobj1, subobj2)
else:
print("~ {0} {1}: {2} => {3}".format(obj1, mkey,
getattr(obj2, mkey),
getattr(obj1, mkey)))
def print_diff(obj1, obj2):
ndiff = obj1.diff(obj2)
print_diff_changed(obj1, obj2, ndiff.changed())
print_diff_added(obj1, obj2, ndiff.added())
print_diff_removed(obj1, obj2, ndiff.removed())
# The last of the lifted-parsing functions
# main()
def main():
# argparse handling
argParser = argparse.ArgumentParser(prog='NmapPoll',
formatter_class=argparse.RawDescriptionHelpFormatter,
description='''Polls hosts with nmap at an interval, reporting any deviations from the
starting scan on a per-host basis.''',
epilog=''' ***NOTE***
You should NOT specify an output file, as this will not allow the parser to
work correctly. Default behavior is to output the start and latest runs in
XML format in your current directory.
Also, please run as root (or with sudo) if you\'ve set a long interval or are
scanning a large number of hosts.''')
argParser.add_argument('--delay','-d',metavar='SECS',
type=int,
default=0,
help='Number of seconds to wait after each scan completion before beginning the next round')
argParser.add_argument('--no-files','-n',
action='store_true',
dest='noFiles',
default=False,
help='Do not write outputs to XML files following the start and latest scans, saving only what it shows on the screen (not recommended!)')
argParser.add_argument('hosts', nargs=1,metavar='HOSTS',
help='Nmap-style host specification (see `man nmap` for more details)')
argParser.add_argument('options', nargs=argparse.REMAINDER,metavar='...',
help='Nmap-style option switches specifying scan type, speed, ports, etc.')
myArgs = argParser.parse_args()
# Please don't try to specify -o switches with libnmap.process - it's
# already doing -oX- to dump XML to stdout
for option in myArgs.options:
if option[0:1] == '-o':
sys.stderr.write('You can not use nmap\'s output specifiers here.')
exit(1)
# Run baseline scan to start
print 'Running initial scan on {0} now ({1}).'.format(myArgs.hosts, str(datetime.now()).split('.',2)[0])
startScan, startScanOut = doScan(myArgs.hosts, ' '.join(myArgs.options))
# Make sure we got a good return
if startScan:
# Write XML outfile if configured to
if not myArgs.noFiles:
with open('startScan.xml', 'w') as f:
try:
f.write(startScanOut)
except IOError as e:
sys.stderr.write('Exception raised while writing file: {0}'.format(e.msg))
sys.stderr.write('Continuing....')
sys.stdout.write('\n')
# Summary of our startscan to give you your instant gratification
prettyOutput(startScan)
sys.stdout.write('\n')
# Run our consecutive scans until we Ctrl+C them
while True:
sys.stdout.write('\n')
# Delay countdown enabling us to provide some output, pretty close
# to accurate doing like this and it's close enough
if myArgs.delay:
thisDelay = myArgs.delay
while thisDelay > 0:
sys.stdout.write('\rWaiting for {0} more seconds before starting...'.format(thisDelay))
sys.stdout.flush()
sleep(1)
thisDelay -= 1
# Overwrite our delay countdown, start latest cyclic scan
sys.stdout.write('\rRunning latest scan on {0} now ({1}).\n'.format(myArgs.hosts, str(datetime.now()).split('.',2)[0]))
sys.stdout.flush()
latestScan, latestScanOut = doScan(myArgs.hosts, ' '.join(myArgs.options))
# Make sure we got a good return
if latestScan:
# Write XML outfile if configured to
if not myArgs.noFiles:
with open('latestScan.xml', 'w') as f:
try:
f.write(latestScanOut)
except IOError as e:
sys.stderr.write('Exception raised while writing file: {0}'.format(e.msg))
sys.stderr.write('Continuing....')
# Show our differences between this run and last run
print_diff(latestScan, startScan)
startScan = latestScan
if __name__ == '__main__':
# extra imports not necessary without main
import argparse
main()