read commands from STDIN if used as pipe
[dell-switch] / find-port-for-hostname
1 #!/bin/sh -e
2
3 host=$1
4
5 test -z "$host" && echo "Usage: $0 hostname" && exit 1
6
7 sudo id >/dev/null
8
9 . ./shm-trunk.regex
10
11 # hide physical and trunk ports (> 10 mac, port nr <= 49)
12 cat /dev/shm/snmp-mac-port/* | cut -d' ' -f1,4 | sort | uniq -c | awk '{ if ( $1 > 10 && $3 <= 49 ) print "/"$2":"$2 " .* " $3 }' > /dev/shm/trunk.regex
13
14 ping -c 1 $host | grep from > /dev/shm/port.$host.ping
15 # did we got resolved IP address?
16 if grep '(' /dev/shm/port.$host.ping >/dev/null ; then
17         ip=`cat /dev/shm/port.$host.ping | cut -d' ' -f5 | tr -d '():'`
18         host=`cat /dev/shm/port.$host.ping | cut -d' ' -f4`
19 else
20         ip=`cat /dev/shm/port.$host.ping | cut -d' ' -f4 | tr -d ':'`
21 fi
22 mac=`sudo arp -a -n | grep "($ip)" | cut -d' ' -f4 | sort -u`
23 if [ -z "$mac" ] ; then
24         bro=`./bro-conn-ip-vlan-mac.sh $ip`
25         echo "# bro $bro"
26         mac=`echo $bro | cut -d' ' -f3`
27         test -z "$mac" && exit 1
28 fi
29 grep -r -i $mac /dev/shm/snmp-mac-port/ | tee /dev/shm/port.$host.switch | grep --file /dev/shm/trunk.regex -v | cut -d: -f2-
30
31 echo "# $host $ip $mac on "`cat /dev/shm/port.$host.switch | cut -d: -f2- | cut -d' ' -f1 | sort -u | wc -l`" switches"