Below is a simple bash script which uses snmpwalk to find out which ports on a Cisco switch (It should work on other as well) aren’t being used, over a period of time. It works by checking if the port is up or down, if it’s up it’ll remove it from the list of ports. For best results, set the script up for a crontab of about 5 to 15 minutes, and then come back in a few weeks to see which ports are inactive.
#!/bin/bash
date
WORKDIR=/root/
IPs=( 10.0.0.1 10.0.0.2 ) #IP addresses seperated by spaces
# Start making indexes if file doesn't exist
for IP in ${IPs[@]} #Loop through list of IPs
do
if [ ! -f $WORKDIR$IP.index ] #If the ip.index file doesn't exist then create it.
then
snmpwalk -v1 -c snmpass $IP 1.3.6.1.2.1.2.2.1.2 > $WORKDIR$IP.index
# We walk this snmp value to get the names of the interface so we can find them on the switch easier
fi
INTERFACES=`cat $WORKDIR$IP.index | sed 's/IF-MIB::ifDescr.//' | sed 's/ = STRING.*//'`
#Get a list of interface IDs
for INTERFACE in $INTERFACES
#Loop though each interface ID
do
if [ `snmpwalk -v1 -c snmpass $IP 1.3.6.1.2.1.2.2.1.8.$INTERFACE | \
sed 's/IF-MIB::ifOperStatus\.[0-9]* = INTEGER: //' | sed 's/([0-9])//'` == "up" ]
#We then sed the snmp results to get up or down state
then
echo Success $IP / $INTERFACE is UP - Removing from list
#We echo if an interface is up
mv $IP.index $WORKDIR$IP.index.tmp
#We need a temp file since we can't read and write at the same time in a pipe
cat $WORKDIR$IP.index.tmp | \
sed "s/IF-MIB::ifDescr.$INTERFACE.*//" > $WORKDIR$IP.index
#remove the interface that is up and pipe it to the index file
rm $WORKDIR$IP.index.tmp #remove the temp index file
fi
done
done
rm $WORKDIR*.index.tmp >/dev/null 2>&1
#Do a quick clean up incase we left some files behind. This should always return an error
