HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Getting MAC addresses from systems

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
systemsgettingaddressesmacfrom

Problem

I have written code to get all the MAC addresses in from systems having multiple MAC addresses and I think there's something which needs to be corrected albeit the code runs fine.

Note: I have just tested it on Android.

import re

def getMacs():
    macs = []
    file = os.popen("getmac").read()
    file = file.split("\n")

    for line in file:
        found = re.search(r'([0-9A-F]{2}[:-]){5}([0-9A-F]{2})', line, re.I)
        if found:
            mac = found.group().replace('-', ':')
            macs.append(mac)

    return macs

Solution

There are a few things that I think could be improved.

Include all required imports

The code uses os.popen() but doesn't import os. It should.

Consider other platforms

On my Linux machine, there is no getmac command, but one could get the required information via ifconfig. Consider either passing the command in to the function or making OS-specific versions.

Don't use deprecated functions

The os.popen() command is deprecated since version 2.6. Use the subprocess module instead.

Context

StackExchange Code Review Q#150324, answer score: 4

Revisions (0)

No revisions yet.