Skip to content

Instantly share code, notes, and snippets.

@ivanleoncz
Created August 11, 2019 02:28
Show Gist options
  • Save ivanleoncz/3a4e53a64a8ca44a72c7594c424e1145 to your computer and use it in GitHub Desktop.
Save ivanleoncz/3a4e53a64a8ca44a72c7594c424e1145 to your computer and use it in GitHub Desktop.
Obtains network data from GNU/Linux Operating Systems.
""" Functions for obtaining network information from a system. """
import subprocess as sp
__version__ = "v1.0"
__author__ = "@ivanleoncz"
def get_nic_ipv4(nic):
"""
Get IP address from a NIC.
Parameter
---------
nic : str
Network Interface Card used for the query.
Returns
-------
ipaddr : str
Ipaddress from the NIC provided as parameter.
"""
result = None
try:
result = sp.check_output(["ip", "-4", "addr", "show", nic],
stderr=sp.STDOUT)
except Exception:
return "Unkown NIC: %s" % nic
result = result.decode().splitlines()
ipaddr = [l.split()[1].split('/')[0] for l in result if "inet" in l]
return ipaddr[0]
def get_nics():
"""
Get all NICs from the Operating System.
Returns
-------
nics : list
All Network Interface Cards.
"""
result = sp.check_output(["ip", "addr", "show"])
result = result.decode().splitlines()
nics = [l.split()[1].strip(':') for l in result if l[0].isdigit()]
return nics
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment