Skip to content

Instantly share code, notes, and snippets.

@pmbuko
Last active August 12, 2018 23:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmbuko/a8454d34bd813c325447 to your computer and use it in GitHub Desktop.
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.
#!/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
@zlatko-minev
Copy link

Nice. On py3.6 MacOS X, you need to decode the string python interfaces.decode('UTF-8')

matches = findall(r' en[\d]+', interfaces.decode('UTF-8'))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment