Código de Python - Clase para configurar el archivo dhcpd.conf de nuestro servidor

Imágen de perfil
Val: 665
Plata
Ha mantenido su posición en Python (en relación al último mes)
Gráfica de Python

Clase para configurar el archivo dhcpd.conf de nuestro servidorgráfica de visualizaciones


Python

estrellaestrellaestrellaestrellaestrella(1)
Publicado el 26 de Junio del 2019 por Xavi
856 visualizaciones desde el 26 de Junio del 2019
Clase para gestionar el archivo dhcpd.conf de nuestro servidor

readFile() -> lea el archivo dhcpd recibido en el constructor y ponga los datos en dos listas
getValue() -> devuelve el valor de la clave recibida
setValue() -> actualizar el valor si existe o agregar un nuevo valor si no existe
removeValue() -> eliminar valores
clearSubnet() -> elimina las subredes creadas o leídas del archivo
newSubnet() -> crea una nueva subred
getSubnetNumber() -> devuelve el número de subredes
getSubnetValue() -> devuelve el valor de la subred indicada
setSubnetValue() -> agregar o actualizar valores de la subred
guardar() -> guardar cualquier cambio en el archivo

Un archivo de configuración es similar a:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
option domain-name "example.org";                               getValue(), setValue()
option domain-name-servers ns1.example.org, ns2.example.org;    getValue(), setValue()
default-lease-time 600;                                         getValue(), setValue()
max-lease-time 7200;                                            getValue(), setValue()
subnet 10.5.5.0 netmask 255.255.255.224 {                       getSubnetNumber(), newSubnet(), clearSubnet(), getSubnetValue()
    range 10.5.5.26 10.5.5.30;                                  setSubnetValue(), getSubnetValue()
    option domain-name-servers ns1.internal.example.org;        setSubnetValue(), getSubnetValue()
    option domain-name "internal.example.org";                  setSubnetValue(), getSubnetValue()
    option routers 10.5.5.1;                                    setSubnetValue(), getSubnetValue()
    option broadcast-address 10.5.5.31;                         setSubnetValue(), getSubnetValue()
    default-lease-time 600;                                     setSubnetValue(), getSubnetValue()
    max-lease-time 7200;                                        setSubnetValue(), getSubnetValue()
}
subnet 10.10.10.0 netmask 255.255.255.0 {                       getSubnetNumber(), newSubnet(), clearSubnet(), getSubnetValue()
    range 10.10.10.200 10.10.10.230;                            setSubnetValue(), getSubnetValue()
    option domain-name-servers 8.8.8.8;                         setSubnetValue(), getSubnetValue()
    option domain-name "internal.example.org";                  setSubnetValue(), getSubnetValue()
    option routers 10.10.10.1;                                  setSubnetValue(), getSubnetValue()
    option broadcast-address 10.10.10.255;                      setSubnetValue(), getSubnetValue()
}

Requerimientos

Python 3
Desarrollado sobre Debian/Ubuntu

0.1

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

0.2
estrellaestrellaestrellaestrellaestrella(1)

Publicado el 27 de Junio del 2019gráfica de visualizaciones de la versión: 0.2
758 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
"""
Class for read or modify dhcpd server config file

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

readFile() -> read dhcpd file received in constructor and put data in two lists
getValue() -> return value from key received
    sample:
        key: "option domain-name-servers"
        return: "option domain-name-servers ns1.example.org, ns2.example.org;"
setValue() -> update the value if exist or add new value if not exists
removeValue() -> remove values
clearSubnet() -> remove the subnets created or readed from file
newSubnet() -> create a new subnet
getSubnetNumber() -> return the number of subnets
getSubnetValue() -> return value of indicated subnet
setSubnetValue() -> add or update values of the subnet
save() -> save any changes to the file

config file is similar to:
    option domain-name "example.org";                               getValue(), setValue()
    option domain-name-servers ns1.example.org, ns2.example.org;    getValue(), setValue()
    default-lease-time 600;                                         getValue(), setValue()
    max-lease-time 7200;                                            getValue(), setValue()
    subnet 10.5.5.0 netmask 255.255.255.224 {                       getSubnetNumber(), newSubnet(), clearSubnet(), getSubnetValue()
        range 10.5.5.26 10.5.5.30;                                  setSubnetValue(), getSubnetValue()
        option domain-name-servers ns1.internal.example.org;        setSubnetValue(), getSubnetValue()
        option domain-name "internal.example.org";                  setSubnetValue(), getSubnetValue()
        option routers 10.5.5.1;                                    setSubnetValue(), getSubnetValue()
        option broadcast-address 10.5.5.31;                         setSubnetValue(), getSubnetValue()
        default-lease-time 600;                                     setSubnetValue(), getSubnetValue()
        max-lease-time 7200;                                        setSubnetValue(), getSubnetValue()
    }
    subnet 10.10.10.0 netmask 255.255.255.0 {                       getSubnetNumber(), newSubnet(), clearSubnet(), getSubnetValue()
        range 10.10.10.200 10.10.10.230;                            setSubnetValue(), getSubnetValue()
        option domain-name-servers 8.8.8.8;                         setSubnetValue(), getSubnetValue()
        option domain-name "internal.example.org";                  setSubnetValue(), getSubnetValue()
        option routers 10.10.10.1;                                  setSubnetValue(), getSubnetValue()
        option broadcast-address 10.10.10.255;                      setSubnetValue(), getSubnetValue()
    }
"""
import os, sys
from subprocess import Popen, PIPE
import glob
import re
 
__ver__="0.2"
 
class Dhcpd():
 
    """ Contain a file name and path to dhcpd server """
    file=""
 
    """ variables that contain the vaues and subnets """
    valuesData=[]
    subnetData=[]
 
    def __init__(self, file):
        """
        Parameters:
            file string - path and file name
        """
        self.file=file
 
    def readFile(self):
        """
        This function read dhcpd file an set data into vars

        Return
            boolean - False if not possible read the file
        """
        self.valuesData=[]
        self.subnetData=[]
        if not self.file or not os.path.exists(self.file):
            return False
 
        inSubnet=False
        subnet=-1
        with open(self.file,"r") as f:
            for line in f:
                line=line.strip()
                if line and line[0]!="#":
                    if len(line)>=7 and line[:7]=="subnet ":
                        inSubnet=True
                        subnet+=1
                        self.subnetData.append([])
                    if inSubnet:
                        self.subnetData[subnet].append(line)
                    else:
                        self.valuesData.append(line)
                    if inSubnet and line and line[0]=="}":
                        inSubnet=False
        return True
 
    def getValue(self, key):
        """
        Function that return a line for a value in dhcpd config file
        Find the text that start line to len the value is same

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

        Parameters:
            key string
            value string
        return:
            integer - [1 updated, 2 insert]
        """
        for i in range(len(self.valuesData)):
            line=self.valuesData[i]
            if len(line)>=len(key) and line[0:len(key)]==key:
                self.valuesData[i]=key+" "+value.strip()
                return 1
        self.valuesData.append(key+" "+value)
        return 2
 
    def removeValue(self, key):
        """
        Function to remove values

        Parameters:
            key string
        return:
            boolean
        """
        for line in self.valuesData:
            if len(line)>=len(key) and line[0:len(key)]==key:
                self.valuesData.remove(line)
                return True
        return False
 
    def clearSubnet(self):
        """
        function that remove the subnets created or readed from file
        """
        self.subnetData=[]
        return self
 
    def newSubnet(self, ip, netmask):
        """
        This function create a new subnet

        Parameters:
            ip string
            netmask string
        Return:
            int - index of new subnet
        """
        newIndex=len(self.subnetData)
        self.subnetData.append([])
        self.subnetData[newIndex].append("subnet {} netmask {}".format(ip, netmask))
        self.subnetData[newIndex].append("{")
        self.subnetData[newIndex].append("}")
        return newIndex
 
    def getSubnetNumber(self):
        """
        Function that return the number of subnets

        Return:
            int
        """
        return len(self.subnetData)
 
    def getSubnetValue(self, index, key):
        """
        Function that return value for subnet

        Parameteres:
            index int - index of subnet
            key string
        Return:
            string
        """
        if len(self.subnetData)==0 or index<0 or index>len(self.subnetData)-1:
            return ""
 
        for line in self.subnetData[index]:
            if len(line)>=len(key) and line[0:len(key)]==key:
                return line
        return ""
 
    def setSubnetValue(self, index, key, value):
        """
        Function to add or update values of the subnet

        Parameters:
            index int - define the subnet index
            key string - key to update or insert
            value string
        Return:
            integer - [1 updated, 2 insert]
        """
        if len(self.subnetData)==0 or index<0 or index>len(self.subnetData)-1:
            return self
        for i in range(len(self.subnetData[index])):
            line=self.subnetData[index][i]
            if len(line)>=len(key) and line[0:len(key)]==key:
                self.subnetData[index][i]=key+" "+value.strip()
                return 1
        self.subnetData[index][-1]=key+" "+value
        self.subnetData[index].append("}")
        return 2
 
    def save(self):
        """
        This function save the file with the changes

        Return:
            int - number of lines saved in a file | -1 not writable file
        """
        if not os.access(self.file, os.W_OK):
            return -1
 
        linesSaved=0
        with open(self.file, "w") as f:
            f.write("# file created from class dhcpd.py\n")
            f.write("# http://lwp-l.com/s5385\n\n")
            for line in self.valuesData:
                linesSaved+=1
                f.write(line+"\n")
            for subnets in self.subnetData:
                for line in subnets:
                    linesSaved+=1
                    f.write(line+"\n")
        return linesSaved



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
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s5385