Código de Python - Clase para configurar la red en 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 configurar la red en Linuxgráfica de visualizaciones


Python

Publicado el 27 de Junio del 2019 por Xavi (548 códigos)
1.061 visualizaciones desde el 27 de Junio del 2019
Clase que permite leer y escribir los archivos de configuración de las interfaces alojados en /etc/network/interfaces.d/

checkInterfacesSource() - Comprueba si el archivo de interfaces tiene una fuente ....
readFiles() - Lee todos los archivos en la carpeta /etc/network/interfaces.d/ y llena el diccionario
getValue() - Obtiene el valor de la interfaz
setValue() - Actualizar o agregar valor
createIface() - crea un iface .... (iface eth0 inet static)
getValueIface() - Obtiene el valor del iface
setValueIface() - Actualizar o agregar un valor en iface
removeIFace() - Eliminar iface
removeInterface() - Eliminar el archivo de la interfaz
save() - Guarda cualquier cambio en los archivos

Un archivo de configuración es similar a:
1
2
3
4
5
6
7
8
auto eth0                       getValue(), setValue()
allow-hotplug eth0              getValue(), setValue()
iface eth0 inet static          createIface(), getValueIface()
    address 192.168.0.102       getValueIface(), setValueIface()
    netmask 255.255.255.0       getValueIface(), setValueIface()
    network 192.168.0.0         getValueIface(), setValueIface()
    broadcast 192.168.0.255     getValueIface(), setValueIface()
    gateway 192.168.0.2         getValueIface(), setValueIface()

Requerimientos

Python 3
Desarrollado sobre Debian/Ubuntu

0.1
estrellaestrellaestrellaestrellaestrella(1)

Publicado el 27 de Junio del 2019gráfica de visualizaciones de la versión: 0.1
1.062 visualizaciones desde el 27 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
"""
Class for read or modify /etc/network/interfaces.d/XXX files
It not preparated for vlans

Last versión:
http://lwp-l.com/s5387

checkInterfacesSource() - Check if interfaces file has a source....
readFiles() - Read al files in /etc/network/interfaces.d/ folder and fill the dictionary
getValue() - Get value of the interface
setValue() - Update or add value
createIface() - create an iface .... (iface eth0 inet static)
getValueIface() - Get value of the iface
setValueIface() - Update or add a value in iface
removeIFace() - Remove iface
removeInterface() - Remove file of the interface
save() - Save any changes to the files

config file is similar to:
    auto eth0                       getValue(), setValue()
    allow-hotplug eth0              getValue(), setValue()
    iface eth0 inet static          createIface(), getValueIface()
        address 192.168.0.102       getValueIface(), setValueIface()
        netmask 255.255.255.0       getValueIface(), setValueIface()
        network 192.168.0.0         getValueIface(), setValueIface()
        broadcast 192.168.0.255     getValueIface(), setValueIface()
        gateway 192.168.0.2         getValueIface(), setValueIface()
"""
 
import os, sys
from subprocess import Popen, PIPE
import glob
import re
 
__ver__="0.1"
 
class Interfaces():
 
    folder="/etc/network/interfaces.d/"
 
    """ list that contain the files with its content
    files
        {fileName1:[[value1, value2], [iface, value1]]},
        {fileName2:[[values], [values iface]]}
    
    """
    files={}
 
    def __init__(self,folder=""):
        if folder:
            self.folder=folder
 
    def checkInterfacesSource(self, file="/etc/network/interfaces", find="source /etc/network/interfaces.d/*"):
        """
        Check if exist "source /etc/network/interfaces.d/*" in /etc/network/interfaces

        Return:
            boolean
        """
        if not os.path.exists(file):
            return False

        with open(file, "r") as f:
            for line in f:
                if line.strip()==find:
                    return True
        return False

    def readFiles(self):
        """
        This function read files in /etc/network/interfaces.d/* an set data into var

        Return
            boolean - False if not possible read the files
        """
        self.files={}

        inIface=False

        for fileName in os.listdir(self.folder):
            self.files[fileName]=[[],[]]
            with open(os.path.join(self.folder,fileName),"r") as f:
                for line in f:
                    line=line.strip()
                    if line and line[0]!="#":
                        if len(line)>=6 and line[:6]=="iface ":
                            inIface=True
                        if inIface:
                            self.files[fileName][1].append(line)
                        else:
                            self.files[fileName][0].append(line)
        return True

    def getValue(self, interface, key):
        """
        Function that return a line for a value of the interface
        Find the text that start line to len the value is same

        Parameteres:
            interface string
            key string
        Return:
            string 
        """
        self._checkInterfaceInFiles(interface)

        for line in self.files[interface][0]:
            if len(line)>=len(key) and line[0:len(key)]==key:
                return line
        return ""
    
    def setValue(self, interface, key, value):
        """
        Function to update value if exist or add new value if not exists

        Parameters:
            interface string
            key string
            value string
        return:
            integer - [1 updated, 2 insert]
        """
        self._checkInterfaceInFiles(interface)

        for i in range(len(self.files[interface][0])):
            line=self.files[interface][0][i]
            if len(line)>=len(key) and line[0:len(key)]==key:
                self.files[interface][0][i]=key+" "+value.strip()
                return 1
        self.files[interface][0].append(key+" "+value)
        return 2
    
    def createIface(self, interface, addressFamily, method):
        """
        Create the iface for a interface

        Parameters:
            interface string
            addressFamily string - inet, inet6, ipx
            method string - static, dhcp
        Return:
            boolean - true if is created | false if exists
        """
        self._checkInterfaceInFiles(interface)

        if len(self.files[interface][1])>0:
            return False

        self.files[interface][1].append("iface {} {} {}".format(interface, addressFamily, method))
        return True

    def removeIFace(self, interface):
        """
        function that remove the iface in a interface

        Parameters:
            interface string
        Return:
            boolean - [True removed|False not exists interface]
        """
        if self.files[interface]:
            self.files[interface][1]=[]
            return True
        return False

    def getValueIface(self, interface, key):
        """
        Function that return a line for a iface in interface
        Find the text that start line to len the value is same

        Parameteres:
            interface string
            key string
        Return:
            string 
        """
        self._checkInterfaceInFiles(interface)

        for line in self.files[interface][1]:
            if len(line)>=len(key) and line[0:len(key)]==key:
                return line
        return ""

    def setValueIface(self, interface, key, value):
        """
        Function to update value if exist or add new value if not exists

        Parameters:
            interface string
            key string
            value string
        return:
            integer - [1 updated|2 insert|-1 not exists iface in this interface. Execute first self.createIface()]
        """
        self._checkInterfaceInFiles(interface)

        if len(self.files[interface][1])==0:
            return -1

        for i in range(len(self.files[interface][1])):
            line=self.files[interface][1][i]
            if len(line)>=len(key) and line[0:len(key)]==key:
                self.files[interface][1][i]=key+" "+value.strip()
                return 1
        self.files[interface][1].append(key+" "+value)
        return 2

    def removeInterface(self, interface):
        """
        Function to remove the interface file and interface in self.files

        Parameters:
            interface string
        Return:
            boolean - False not remove the file
        """
        if not os.access(os.path.join(self.folder, interface), os.W_OK):
            return False
        
        try:
            os.remove(os.path.join(self.folder, interface))
            del self.files[interface]
            return True
        except:
            return False

    def _checkInterfaceInFiles(self, interface):
        """
        Check if interface exists in dictionary self.files. if it does not exist it creates it

        Parameters:
            interface string
        """
        if not interface in self.files:
            self.files[interface]=[[], []]
            return False
        return True

    def save(self):
        """
        This function save the files with the changes

        Return:
            int - number of files saved | -1 not writable file
        """
        if not os.access(self.folder, os.W_OK):
            return -1

        filesSaved=0
        for file in self.files:
            if self.files[file][0]==[] and self.files[file][1]==[]:
                continue
            with open(os.path.join(self.folder,file), "w") as f:
                filesSaved+=1
                f.write("# file created from class interfaces.py\n")
                f.write("# http://lwp-l.com/s5387\n\n")
                for line in self.files[file][0]:
                    f.write(line+"\n")
                for line in self.files[file][1]:
                    f.write(line+"\n")
        return filesSaved



Comentarios sobre la versión: 0.1 (1)

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

Comentar la versión: 0.1

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/s5387