Short description for repo.or.cz.
[snmpsar.git] / routemon.sh
blobfeea6f4dbb6a2cf822042da34b84c5ce3115120e
1 #!/bin/bash
3 # vi: set softtabstop=4 shiftwidth=4 tabstop=8 expandtab:
5 # Creates logfiles to track the nexthop for a list of dynamic routes.
7 usage()
9 echo "usage: $0 -d logdir -r routelist -s snmpconffile" 1>&2
10 exit 1
13 # routines for converting a prefix to a netmask
14 dooctet()
16 local prefix=$1
17 local bytenum=$2
18 prefix=$((prefix - 8*bytenum))
19 [ $prefix -ge 8 ] && echo 255 && return
20 echo $((256 - 2**(8-$prefix)))
23 dooctets()
25 local prefix=$1
26 shift
27 for i in $*
29 dooctet $prefix $i
30 done | tr '\012' . | sed 's,.$,\n,'
33 prefix2octets()
35 dooctets $1 0 1 2 3
37 prefix2octets_reversed()
39 dooctets $1 3 2 1 0
43 routelist=
44 outdir=
45 snmpconf=
47 while getopts "d:r:s:" option
49 case "$option" in
50 d) outdir=$OPTARG ;;
51 r) routelist=$OPTARG ;;
52 s) snmpconf=$OPTARG ;;
53 *) usage ;;
54 esac
55 done
57 if [ -n "$routelist" ] && [ -n "$outdir" ] && [ -n "$snmpconf" ]
58 then
60 else
61 echo "Missing parameters." 1>&2
62 usage
65 if [ ! -r "$routelist" ]
66 then
67 echo "Can't read route list '$routelist'." 1>&2
68 exit 1
71 snmpargs=$(cat "$snmpconf") || {
72 echo "Can't read SNMP argument file '$snmpconf'." 1>&2
73 exit 1
76 if [ ! -d "$outdir" ]
77 then
78 echo "Output directory '$outdir' does not exist." 1>&2
79 exit 1
82 stamp="$(date +%Y-%m-%d/%H:%M:%S/%s)"
84 while read name router route nexthops
86 case "$name" in
87 ""|"#"*) continue ;;
88 esac
90 # 10.11.7.0/26 -> 10.11.7.0.192.255.255.255
91 ip=${route%/*}
92 prefix=${route#*/}
93 revmask=$(prefix2octets_reversed "$prefix")
94 target="$ip.$revmask"
96 # -Ov: display value only, not OID name
97 # -Oq: display value only, not type
98 nexthop=$(snmpwalk -Ov -Oq $snmpargs "$router" \
99 "IP-FORWARD-MIB::ipCidrRouteNextHop.$target")
101 # Now figure out which nexthop it's using.
102 # 0 for none, 1 for first nexthop, 2 for second, -1 for unexpected nexthop
103 if [ -z "$nexthop" ]
104 then
105 hopcode=-1
106 hopdescription=snmp-failure
107 elif echo "$nexthop" | grep -q -i "no such instance"
108 then
109 # We treat this as the route not existing, but it could also
110 # mean the SNMP instance doesn't have IP-FORWARD-MIB.
111 hopcode=0
112 hopdescription=route-not-found
113 else
114 hopcode=-1
115 hopdescription=$nexthop
117 index=1
118 for candidate in $nexthops
120 if [ "$candidate" = "$nexthop" ]
121 then
122 hopcode=$index
123 break
125 index=$((index + 1))
126 done
129 if ! echo "$stamp $hopcode $hopdescription" >> "$outdir/$name"
130 then
131 echo "Can't write to $outdir/$name." 1>&2
132 exit 1
134 done < "$routelist"