

Sometimes we have a need to figure out which port, on a network switch, a given device is plugged into. In “Part 1” here we assume we have a single switch on our LAN. “Part 2” will go a little deeper and check multiple switches.
Using this script, we can search by hostname, IP address, or MAC address. The MAC address is the key to success so, if searching by hostname or IP address, we need to first find the MAC address.
We use the “arp” command to check our arp cache for the MAC address. To ensure the MAC address is in the arp cache, we first “ping” the device. Once the “ping” is complete, we use “arp -an” to list the cache and a little awk magic to extract the address we are looking for.
Now that we have the MAC address, we use “snmpwalk” to find the OID for the MAC address. Once we have that, then we use “snmpget” to grab the port related to that OID.
#!/bin/bash
# Shell script to find which siwtch port a compiter is plugged into using
# SNMP.
# -------------------------------------------------------------------------
# Copyright (c) 2012 Jay C, Everson
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# DEVICE = IP address of a managed switch with SNMP enabled
DEVICE="10.1.10.2"
# COMMUNITY = The community string for read-only access to the switch
COMMUNITY="public"
#OID = The out used to find the given address (this should not need to be changed
OID=".1.3.6.1.2.1.17.4.3.1.1"
#Check for proper usage
if [ $# != 2 ]
then
echo "Usage: $0 [-h Hostname] || [-p IP Address} || [-m Mac Address]"
exit
fi
case $1 in
-h)
NAME=$2
IP=`dig $NAME +short | awk '{sub(/\.$/,"",$1); print}'`
# Ping IP address to ensure it is in the arp cache, so we can get the MAC address
CMD=`ping -c 1 -W 1 "$IP" 2>&1`
if [ $? == 0 ]; then
MAC=`/sbin/arp -an | awk "/$IP/"'{print toupper($4)}'`
if [ -z "$MAC" ]
then
echo "Mac address for $2 not found using $IP"
exit
fi
# echo "Found Mac Address: $MAC for IP $IP"
else
echo "$NAME is not responding on IP:$IP."
exit
fi
;;
-p)
IP="$2"
CMD=`ping -c 1 -W 1 "$IP" 2>&1`
if [ $? == 0 ]; then
MAC=`/sbin/arp -an | awk "/$IP/"'{print toupper($4)}'`
if [ -z "$MAC" ]
then
echo "Mac address for $IP not found"
exit
fi
else
echo "$IP is not responding."
exit
fi
;;
-m)
MAC=`echo $2 | awk '{print toupper($0)}'`
;;
*)
echo "Invalid Argument. Usage: $0 [-p IP Address} || [-m Mac Address]"
exit
;;
esac
TARGET=`snmpwalk -Os -c $COMMUNITY -v 2c $DEVICE $OID | awk '{print $1" -- "$4":"$5":"$6":"$7":"$8":"$9}' | awk -v mac=$MAC '$3 == mac {print $1}'`
if [ -n "$TARGET" ]
then
TARGET=${TARGET/mib-2.17.4.3.1.1/mib-2.17.4.3.1.2}
PORT=`snmpget -Os -c $COMMUNITY -v 2c $DEVICE $TARGET | awk '{print $4}'`
# Some switches you may need to manipulate the port number slightly
# for example, on some Cisco switches you need to subtract 48 to get the right port number i.e.
# let "PORT=$PORT-48"
echo "$2 is on port $PORT"
exit
fi
echo "$2 not found"