#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Class for get informatión from network
Last versión:
http://lwp-l.com/s5378
getInterfaces() -> return all interfaces from our system
interfaceIsDhcp() -> return true if interface is configured for get network from dhcp server
getMac() -> return MAC address of the interface
getIp() -> return ip address of the interface
getGateway() -> return gateway address of the interface
getDNS() -> return a list with DNSs of the internface
getBroadcast() -> return broadcast address of the interface
getState() -> return string with state of interface
"""
import os, sys
from subprocess import Popen, PIPE
import glob
import re
__ver__="0.2"
class Net():
def __init__(self):
pass
def getInterfaces(self,allInterfaces=False):
"""
Function that return interfaces
Parameters:
allInterfaces boolean. If is True, return the interfaces active and inactive
Return:
list
"""
try:
if allInterfaces:
result=(Popen("/bin/netstat -ia | awk {'print $1'} | tail -n +3", shell=True, stdin=PIPE, stdout=PIPE).communicate()[0]).strip().splitlines()
else:
result=(Popen("/bin/netstat -i | awk {'print $1'} | tail -n +3", shell=True, stdin=PIPE, stdout=PIPE).communicate()[0]).strip().splitlines()
# convert binary result to string
return list(map(lambda x: x.decode("ascii"), result))
except:
return []
def interfaceIsDhcp(self, interface):
"""
Function that check if interface is configure with dhcp
If interface isn't exist in system return False
Parameters:
interface string - interface name
Return:
boolean
"""
if self.interfaceIsDhcp_interfacesPID(interface):
return True
if self.interfaceIsDhcp_interfacesFile(interface):
return True
return False
def interfaceIsDhcp_interfacesPID(self, interfaces):
"""
Function that check if interface is configured with dhcp in /var/run/dhclient-.....pid
If interface isn't exist in system return False
Parameters:
interface string - interface name
Return:
boolean
"""
files=glob.glob("/var/run/dhclient-*.pid")
if len(files):
if interfaces==files[0][18:-4]:
return True
return False
def interfaceIsDhcp_interfacesFile(self, interface):
"""
Function that check if interface is configured with dhcp in /etc/network/interfaces file
If interface isn't exist in system return False
Parameters:
interface string - interface name
Return:
boolean
"""
if interface in self.getInterfaces(True):
try:
result1=(Popen("grep ^'iface %s inet dhcp' /etc/network/interfaces" % interface, shell=True, stdin=PIPE, stdout=PIPE).communicate()[0]).strip()
result2=(Popen("grep ^'iface %s' /etc/network/interfaces" % interface, shell=True, stdin=PIPE, stdout=PIPE).communicate()[0]).strip()
if result1=="iface %s inet dhcp" % interface or result2=="":
return True
except:
pass
return False
def _getIpAddrShow(self, interface):
"""
Function that return a result for command: ip addr show interface
Parameters:
interface string - interface name
Return:
list with command result
"""
result=[]
if interface in self.getInterfaces():
try:
result=(Popen("ip addr show %s" % interface, shell=True, stdin=PIPE, stdout=PIPE).communicate()[0]).strip().splitlines()
result = list(map(lambda x: x.decode("ascii"), result))
except:
pass
return result
def _getNmcliData(self, interface, data):
"""
Function that call nmcli function
Parameters:
interface string - interface name
data string - field to send to the nmcli function (-f data)
Return:
list
"""
if interface in self.getInterfaces(True):
try:
result=(Popen("nmcli -f {} device show {}".format(data, interface), shell=True, stdin=PIPE, stdout=PIPE).communicate()[0]).strip().splitlines()
return list(map(lambda x: x.decode("ascii").split(":",1)[1].strip(), result))
except:
pass
return []
def getMac(self,interface):
"""
Funcion that return the interface MAC address
Parameters:
interface string - interface name
Return:
string with mac address. If not exist interface, return ""
"""
path="/sys/class/net/{}/address".format(interface)
content=""
if os.path.exists(path):
with open(path, 'r') as f:
content = f.read()
return content.strip()
def getIp(self, interface):
"""
Function that return the interface IP address
Parameters:
interface string - interface name
Return:
string with IP address. If not exist interface or not have ip, return ""
"""
# return same as: 192.168.0.12/24
result=self._getNmcliData(interface, "IP4.ADDRESS")
try:
if result[0]:
return result[0].split("/")[0].strip()
except:
pass
return ""
def getGateway(self, interface):
"""
Function that return the gateway IP address
Parameters:
interface string - interface name
Return:
string with IP address. If not exist interface or not have ip, return ""
"""
# return same as: 192.168.1.1
# --
result=self._getNmcliData(interface, "IP4.GATEWAY")
try:
if result[0]=="--":
return ""
return result[0]
except:
pass
return ""
def getDNS(self, interface):
"""
Function that return the DNS IPs address
Parameters:
interface string - interface name
Return:
list with IP address. If not exist interface or not have ip, return []
"""
return self._getNmcliData(interface, "IP4.DNS")
def getBroadcast(self, interface):
"""
Function that return the broadcast IP address
Parameters:
interface string - interface name
Return:
string with IP address. If not exist interface or not have ip, return ""
"""
# Recorremos todas las lineas recibidas
lines=self._getIpAddrShow(interface)
for line in lines:
try:
if line.strip().split()[0]=="inet":
# sample: inet 192.168.0.12/24 brd 192.168.0.255 scope global dynamic noprefixroute eno1
result=re.findall("brd ([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3})", line)
if result:
return result[0]
except:
pass
return ''
def getState(self, interface):
"""
Function that return the DNS IPs address
Parameters:
interface string - interface name
Return:
string with state
"""
result=self._getNmcliData(interface, "GENERAL.STATE")
if result:
return result[0]
return ""
Comentarios sobre la versión: 0.2 (1)