aboutsummaryrefslogtreecommitdiff
path: root/bin/nwatch
blob: d3161653d86d77f82f64274023a9b0be27f0721d (plain) (blame)
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
#!/usr/bin/env bash

#
# nwatch(1) -- Slightly friendlier version of the suggested script in the
# manual page for ndiff(1) from the Nmap suite, implemented in Bash.
#
# Usage:
#     $ nwatch HOSTLIST CACHEDIR
# Example with root privileges:
#     # nwatch /etc/nwatch.mynet /var/cache/nwatch/mynet
#
# Prints the results of an ndiff(1) call against the last known scan to stdout;
# intended to be called from cron(8):
#     0 0 * * 0  nwatch /etc/nwatch.mynet /var/cache/nwatch/mynet
#
# I recommend you use croncrypt(1), so you don't leak your network information
# in plain text in your email: <https://github.com/tejr/croncrypt>
#
# Please also consider whether your scan actually requires root privileges, and
# could not instead be run by a dedicated user with appropriately limited
# privileges.
#
# Author: Tom Ryder <tom@sanctum.geek.nz>
# Copyright: 2014
# License: GPLv2 (same as Nmap itself)
#

# Defensive umask by default; change at your own risk!
umask 0077

# Some fixed values
self=nwatch
hostlist=${1:?}
cachedir=${2:?}
latest=$cachedir/${self}.scan.latest

# If the cachedir doesn't exist, attempt to create it, otherwise give up
if [[ ! -d "$cachedir" ]] ; then
    if ! mkdir -- "$cachedir" ; then
        exit
    fi
fi

# Today's values
date=$(date +%s)
cache=$cachedir/${self}.scan.${date}
diff=$cachedir/${self}.diff.${date}

# Run the scan or give up
if ! nmap -T4 -v -iL "$hostlist" -oA "$cache" >/dev/null ; then
    exit
fi

# If the link to the XML file is legible, run the diff or give up
if [[ -r ${latest}.xml ]] ; then
    if ! ndiff -- "$latest".xml "$cache".xml > "$diff" ; then
        exit
    fi
fi

# Create or update the links
rm -f "${cache/$date/latest}".*
for cachetype in "$cache".* ; do
    ln -s -- "$cachetype" "${cachetype/$date/latest}"
done

# Write diff to stdout if it exists (not an error if it doesn't)
if [[ -r $diff ]] ; then
    cat -- "$diff"
fi