Skip to content

Instantly share code, notes, and snippets.

@masasin
Created September 12, 2015 10:17
Show Gist options
  • Save masasin/720ecb1b0ecc235b5406 to your computer and use it in GitHub Desktop.
Save masasin/720ecb1b0ecc235b5406 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Get a list of network interfaces on Linux
# Copyright © 2015 Jean Nassar
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
Get a list of network interfaces on Linux.
This code is compatible with Python versions 2 and 3.
"""
from collections import namedtuple
import re
import subprocess
def get_interfaces(external=False, ip=False):
"""
Get a list of network interfaces on Linux.
To access the MAC address and/or the IP address, set the relevant keyword
arguments to True.
Parameters
----------
external : bool, optional
Only show external interfaces, and ignore virtual (e.g. loopback)
devices, and return their MAC addresses.
ip : bool, optional
Only show interfaces which are UP and have an IP address, and return
their IPv4 addresses.
Returns
-------
interfaces
list of str containing the interface name by default, or list of
namedtuple containing `name`, `mac`, and `ip` as requested.
Examples
--------
>>> print(get_interfaces())
['eth0', 'lo', 'wlan0']
>>> print(get_interfaces(external=True))
[Interface(name='eth0', mac='a0:b1:c2:d3:e4:f5'), Interface(name='wlan0', ma
c='f5:e4:d3:c2:b1:a0')]
>>> print(get_interfaces(ip=True))
[Interface(name='lo', ip='127.0.0.1'), Interface(name='wlan0', ip='192.168.1
1.2')]
>>> print(get_interfaces(external=True, ip=True))
[Interface(name='wlan0', mac='f5:e4:d3:c2:b1:a0', ip='192.168.11.2')]
"""
name_pattern = "^(\w+)\s"
mac_pattern = ".*?HWaddr[ ]([0-9A-Fa-f:]{17})" if external else ""
ip_pattern = ".*?\n\s+inet[ ]addr:((?:\d+\.){3}\d+)" if ip else ""
pattern = re.compile("".join((name_pattern, mac_pattern, ip_pattern)),
flags=re.MULTILINE)
ifconfig = subprocess.check_output("ifconfig").decode()
interfaces = pattern.findall(ifconfig)
if external or ip:
Interface = namedtuple("Interface", "name {mac} {ip}".format(
mac="mac" if external else "",
ip="ip" if ip else ""))
return [Interface(*interface) for interface in interfaces]
else:
return interfaces
if __name__ == "__main__":
interfaces = get_interfaces(external=True, ip=True)
for interface in interfaces:
print("{name}: {ip}".format(name=interface.name, ip=interface.ip))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment