Home > Software design >  Using regex to get MAC address from ifConfig
Using regex to get MAC address from ifConfig

Time:09-23

I am trying to grep through my ifconfig output.

def cleanOutput(output):
    print("here6")
    print(output)
    print(type(output))
    output = re.findall('^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$',output)
    print("here7")
    print(output)

This may be awkward as you could do:

ifconfig eth0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'

or a derivative , but since I am getting this info from a file this is not possible.

Actual Output:

here6
ens18: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 15.16.55.4  netmask 255.255.255.0  broadcast 15.16.55.255
        inet6 fe80::6857:e6ff:fe6e:9e5e  prefixlen 64  scopeid 0x20<link>
        ether 6a:57:e6:6e:9e:5e  txqueuelen 1000  (Ethernet)
        RX packets 212358  bytes 14855042 (14.1 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 16308  bytes 1183544 (1.1 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0


<type 'str'>
here7
[]

Expected Output:

6a:57:e6:6e:9e:5e

CodePudding user response:

What about using simple string manipulation:

output = """ens18: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 15.16.55.4  netmask 255.255.255.0  broadcast 15.16.55.255
        inet6 fe80::6857:e6ff:fe6e:9e5e  prefixlen 64  scopeid 0x20<link>
        ether 6a:57:e6:6e:9e:5e  txqueuelen 1000  (Ethernet)
        RX packets 212358  bytes 14855042 (14.1 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 16308  bytes 1183544 (1.1 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0"""


for line in output.splitlines():
    if line.strip().startswith("ether"):
        mac = line.strip().split(" ")[1]
        # mac is '6a:57:e6:6e:9e:5e'
  • Related