Ruth Edges
Ruth Edges

Reputation: 147

Using regex to get MAC address from ifConfig

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

Upvotes: 0

Views: 312

Answers (2)

ADecostre
ADecostre

Reputation: 41

There are many ways to do it, but personally, I have been using the following regex:

device_mac = re.search('(?<=ether )(\w+):(\w+):(\w+):(\w+):(\w+):(\w+)', output).group(0)

So, following @OCa suggestion, below is my test script

import re

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"""

device_mac = re.search('(?<=ether )(\w+):(\w+):(\w+):(\w+):(\w+):(\w+)', output).group(0)

print(device_mac)

And the output:

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

Upvotes: 1

Szabolcs
Szabolcs

Reputation: 4106

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'

Upvotes: 1

Related Questions