Creative Commons License

This work is licenced under a Creative Commons Licence.

User login

Linking MAC Addresses to Hostnames

If you have many servers or other devices plugged into your network devices, and people have been remiss in the past in their labelling of ports, you can end up in a situation where you have no idea what is connected to what. Particualrly for large switches with hundreds of ports, this is unnacceptable. A common method (and I believe the correct method) for solving this problem is using LLDP, but if you have hundreds of servers without LLDP installed (and for whatever reason are unable/unwilling to install it), it is of little to no use.

I was faced with this situation so scrathed together the following bash script to take a list of mac addresses (grabbed from the switch with a 'show macs') and look up these addresses on the dhcp server to find their IP address, and then look up those IPs in DNS. It's an ugly hack, and nowhere near as reliable as LLDP, but the following script might be of use to someone else in the future. Note, as it was intended as a single use script, there are a few assumptions about formats and files that might not hold for your input data. The only dependancy is a working 'host' command in your $PATH and running the script with Bash. One of the largest assumptions is that your network device prints the mac address in the format "001122-334455" - if it does not, you will want to edit the mac_convert function.

# dependancies: `host` command
# fragile, and written for single use only, so may or may not work for you.


function die {
        if command -v date &> /dev/null ; then
                echo -n "$(date +%Y/%m/%d-%H:%M:%S) $1" 1>&2
                exit 1
                echo -n "$1" 1>&2
                exit 1

function mac_convert {
        #takes mac address in format 012345-678910
        #converts to 01:23:45:67:89:10 in variable name $mac

        #very basic check to make sure we have a mac address presented
        (( $# != 1 )) && die "Either no mac supplied, or too many macs supplied to mac_convert"


while read premac interface garbage
        #convert mac
        mac_convert $premac && \
        #look for mac in dhcpd.conf
		#Note the -A1, as our dhcpd.conf holds the IP address on the line after the mac address
        grep_output="$(grep -A1 -i $mac $dhcpdconf)"

        ip_address=${grep_output##* }   #remove leading "fixed address"
        ip_address=${ip_address/;/ }            #remove trailing semi-colon

        #lookup hostname
        if [[ -n "$ip_address" ]]; then
                host_output=$(host $ip_address)
                hostname="${host_output##* }"
                echo "$hostname appears to be attached to $interface"
done < $mac_list        
#$mac_list needs to be: premac interface 
# Any columns after the interface column are ignored, though stored in the "garbage" variable.