Last active
August 12, 2018 23:43
-
-
Save pmbuko/a8454d34bd813c325447 to your computer and use it in GitHub Desktop.
This python script returns a list of active ethernet interfaces in their service priority order. OS X only, as it depends on the 'networksetup' command.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from re import findall | |
from subprocess import check_output | |
def getOrderedInterfaces(): | |
"""Returns all ethernet interfaces in service order.""" | |
interfaces = check_output(['networksetup', '-listnetworkserviceorder']) | |
matches = findall(r' en[\d]+', interfaces) | |
return [ i.lstrip(' ') for i in matches ] | |
def isActive(interface): | |
"""Tests if an interface has an ip address.""" | |
try: | |
address = check_output(['ipconfig', 'getifaddr', interface]) | |
return True | |
except: | |
return False | |
result = [ x for x in getOrderedInterfaces() if isActive(x) ] | |
print result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice. On py3.6 MacOS X, you need to decode the string
python interfaces.decode('UTF-8')