Código de Python - Clase para obtener información de la red sobre Linux

Imágen de perfil
Val: 666
Bronce
Ha disminuido 1 puesto en Python (en relación al último mes)
Gráfica de Python

Clase para obtener información de la red sobre Linuxgráfica de visualizaciones


Python

Actualizado el 27 de Junio del 2019 por Xavi (548 códigos) (Publicado el 21 de Junio del 2019)
3.284 visualizaciones desde el 21 de Junio del 2019
Clase para obtener información de nuestras tarjetas de red

getInterfaces() -> devuelve todas las interfaces de nuestro sistema
interfaceIsDhcp() -> devuelve true si la interfaz está configurada para obtener la red desde el servidor dhcp
getMac() -> devuelve la dirección MAC de la interfaz
getIp() -> devuelve la dirección ip de la interfaz
getGateway() -> devuelve la dirección de la puerta de enlace de la interfaz
getDNS() -> devuelve una lista con los DNS de la interfaz interna
getBroadcast() -> devuelve la dirección de transmisión de la interfaz
getState() -> devuelve una cadena con el estado de la interfaz

Esta probado sobre Debian/Ubuntu

Requerimientos

Python 3

0.1

Publicado el 21 de Junio del 2019gráfica de visualizaciones de la versión: 0.1
388 visualizaciones desde el 21 de Junio del 2019

0.2
estrellaestrellaestrellaestrellaestrella(1)

Publicado el 26 de Junio del 2019gráfica de visualizaciones de la versión: 0.2
2.897 visualizaciones desde el 26 de Junio del 2019
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#!/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)

Imágen de perfil
27 de Junio del 2019
estrellaestrellaestrellaestrellaestrella
Super útil!!!
Responder

Comentar la versión: 0.2

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s5378