Ubuntu – Bash script to pull all interface MAC address

bashmacscripts

I'm looking to create a bash script that I can use with live Ubuntu 16. I work in a manufacturing facility with multiple different type of board manufacturers and a lot of our customers request the MAC addresses of their system before it ships out. This could be anywhere from 1 to 10 Network interfaces and the amount of systems is anywhere from 1 to hundreds.

How would iIcreate a script to push this info out in order of network interfaces such as:

LAN1 MAC | LAN2 MAC | LAN3 MAC | etc.. etc..

So far I have written a simple script that will list all the MAC addresses for all interfaces but how can i put them in the order i want and make sure the script knows to start at LAN1 then move to LAN2…?

#!/bin/bash

MAC1=$(ip a |awk '/ether/ {print $2}')

echo "$MAC"

#end

Thank you for your help!

Best Answer

As xhienne mentioned, it is sufficient to use ip link with a few filtering techniques. Personally, I use awk.

$ ip -o link  | awk '{print $2,$(NF-2)}'                                                                                 
lo: 00:00:00:00:00:00
eth3: f0:76:1c:8c:6d:f7
wlan7: d0:53:49:3d:53:fd
docker0: 02:42:bc:cd:0b:4d

If so desired , it can be also done with any other language, for example python:

$ cat get_iface_mac.py                                                                                                   
#!/usr/bin/env python
from __future__ import print_function
import netifaces as ni
for iface in ni.interfaces():
     print(iface + " " + ni.ifaddresses(iface)[ni.AF_LINK][0]['addr'])

$ ./get_iface_mac.py                                                                                                     
lo 00:00:00:00:00:00
eth3 f0:76:1c:8c:6d:f7
wlan7 d0:53:49:3d:53:fd
docker0 02:42:bc:cd:0b:4d
Related Question