1 | import lliurex.net |
---|
2 | import lliurex.interfacesparser |
---|
3 | import subprocess |
---|
4 | import os |
---|
5 | import tempfile |
---|
6 | import shutil |
---|
7 | import time |
---|
8 | import tarfile |
---|
9 | class NetworkManager: |
---|
10 | def __init__(self): |
---|
11 | self.path_interfaces = '/etc/network/interfaces' |
---|
12 | self.interfaces = lliurex.interfacesparser.InterfacesParser() |
---|
13 | self.interfaces.load(self.path_interfaces) |
---|
14 | self.backup_files=["/etc/network/interfaces", "/etc/init/network-manager.override"] |
---|
15 | self.rules_file="/etc/udev/rules.d/70-persistent-net.rules" |
---|
16 | |
---|
17 | |
---|
18 | #def __init__ |
---|
19 | def startup(self,options): |
---|
20 | self.internal_interface = objects['VariablesManager'].get_variable('INTERNAL_INTERFACE') |
---|
21 | self.external_interface = objects['VariablesManager'].get_variable('EXTERNAL_INTERFACE') |
---|
22 | #def startup |
---|
23 | |
---|
24 | def get_interfaces(self): |
---|
25 | return {'status':True,'msg':[x['name'] for x in lliurex.net.get_devices_info()]} |
---|
26 | #def get_interfaces |
---|
27 | |
---|
28 | def get_interfaces_network_file(self): |
---|
29 | return {'status':True,'msg':self.interfaces.get_list_interfaces()} |
---|
30 | #def get_interfaces_network_file |
---|
31 | |
---|
32 | |
---|
33 | |
---|
34 | def load_network_file(self): |
---|
35 | try: |
---|
36 | self.interfaces.load('/etc/network/interfaces') |
---|
37 | except Exception as e: |
---|
38 | if "not exists" in e.message : |
---|
39 | return {'status':False,'msg':'File not exist'} |
---|
40 | |
---|
41 | return {'status':True,'msg':'Reload file'} |
---|
42 | #def load_network_file |
---|
43 | |
---|
44 | def set_internal_interface(self, interface): |
---|
45 | objects['VariablesManager'].init_variable('INTERNAL_INTERFACE',{'internal_interface':interface}) |
---|
46 | self.internal_interface = interface |
---|
47 | |
---|
48 | ip = None |
---|
49 | netmask = None |
---|
50 | listinfo = self.interfaces.get_info_interface(interface) |
---|
51 | for stanza in listinfo: |
---|
52 | if(stanza.__class__.__name__ == 'StanzaIface'): |
---|
53 | if (stanza.method == 'static' ): |
---|
54 | for option in stanza.options: |
---|
55 | if (option.startswith('address')): |
---|
56 | try: |
---|
57 | ip = option.split(" ")[1] |
---|
58 | except Exception as e: |
---|
59 | pass |
---|
60 | if (option.startswith('netmask')): |
---|
61 | try: |
---|
62 | netmask = option.split(" ")[1] |
---|
63 | except Exception as e: |
---|
64 | pass |
---|
65 | if(ip == None): |
---|
66 | ip = lliurex.net.get_ip(interface) |
---|
67 | if(netmask == None): |
---|
68 | netmask = lliurex.net.get_netmask(interface) |
---|
69 | |
---|
70 | if (ip != None and netmask != None): |
---|
71 | objects['VariablesManager'].init_variable('INTERNAL_NETWORK',{'ip':ip,'netmask':netmask}) |
---|
72 | objects['VariablesManager'].init_variable('INTERNAL_MASK',{'internal_mask':netmask}) |
---|
73 | objects['VariablesManager'].init_variable('SRV_IP',{'ip':ip}) |
---|
74 | return {'status':True,'msg':'internal interface'} |
---|
75 | #def set_internal_interfaces |
---|
76 | |
---|
77 | def set_external_interface(self, interface): |
---|
78 | objects['VariablesManager'].init_variable('EXTERNAL_INTERFACE',{'external_interface':interface}) |
---|
79 | self.external_interface = interface |
---|
80 | return {'status':True,'msg':'external interface'} |
---|
81 | #def set_external_interface |
---|
82 | |
---|
83 | def interface_dhcp(self, interface, otf): |
---|
84 | if interface == self.internal_interface: |
---|
85 | return {'status':False,'msg':'Interface ' + interface + " is impossible set to dhcp"} |
---|
86 | if otf: |
---|
87 | os.system('dhclient ' + interface) |
---|
88 | |
---|
89 | if interface in self.interfaces.get_list_interfaces(): |
---|
90 | self.interfaces.change_to_dhcp(interface) |
---|
91 | else: |
---|
92 | aux_stanza_auto = lliurex.interfacesparser.StanzaAuto([interface]) |
---|
93 | aux_stanza_dhcp = lliurex.interfacesparser.StanzaIface([interface],"inet dhcp") |
---|
94 | self.interfaces.insert_stanza(aux_stanza_auto) |
---|
95 | self.interfaces.insert_stanza(aux_stanza_dhcp) |
---|
96 | self.interfaces.write_file(self.path_interfaces) |
---|
97 | return {'status':True,'msg':'Interface ' + interface + " has been changed to dhcp"} |
---|
98 | |
---|
99 | def interface_static(self, interface, ip,netmask,otf, gateway=None,dnssearch=None): |
---|
100 | if otf: |
---|
101 | os.system('ifconfig '+ interface+' ' + ip + ' netmask ' + netmask) |
---|
102 | if gateway != None: |
---|
103 | os.system('route add default gw ' + gateway) |
---|
104 | if interface in self.interfaces.get_list_interfaces(): |
---|
105 | options = {'address':ip ,'netmask':netmask} |
---|
106 | if gateway != None: |
---|
107 | options['gateway'] = gateway |
---|
108 | if dnssearch != None: |
---|
109 | options['dns-search'] = dnssearch |
---|
110 | self.interfaces.change_to_static(interface,options) |
---|
111 | else: |
---|
112 | |
---|
113 | options = [] |
---|
114 | if gateway != None: |
---|
115 | options.append("gateway " + gateway) |
---|
116 | if dnssearch != None: |
---|
117 | options.append("dns-search " + dnssearch) |
---|
118 | aux_stanza_auto = lliurex.interfacesparser.StanzaAuto([interface]) |
---|
119 | aux_stanza_static = lliurex.interfacesparser.StanzaIface([interface],"inet dhcp") |
---|
120 | aux_stanza_static.change_to_static(ip,netmask,options) |
---|
121 | self.interfaces.insert_stanza(aux_stanza_auto) |
---|
122 | self.interfaces.insert_stanza(aux_stanza_static) |
---|
123 | |
---|
124 | self.interfaces.write_file(self.path_interfaces) |
---|
125 | if interface == self.internal_interface: |
---|
126 | objects['VariablesManager'].init_variable('INTERNAL_NETWORK',{'ip':ip,'netmask':netmask}) |
---|
127 | objects['VariablesManager'].init_variable('INTERNAL_MASK',{'internal_mask':netmask}) |
---|
128 | objects['VariablesManager'].init_variable('SRV_IP',{'ip':ip}) |
---|
129 | |
---|
130 | # Restarting internal interface. Initialization behaves better this way |
---|
131 | os.system("ifdown %s; ifup %s"%(interface,interface)) |
---|
132 | |
---|
133 | |
---|
134 | return {'status':True,'msg':'Interface ' + interface + " has been changed to static "} |
---|
135 | |
---|
136 | |
---|
137 | def get_info_eth(self,eth): |
---|
138 | if type(eth) == type(""): |
---|
139 | return {'status':True,'msg':lliurex.net.get_device_info(eth)} |
---|
140 | else: |
---|
141 | return {'status':False,'msg':'eth must to be string'} |
---|
142 | #def get_info_eth |
---|
143 | |
---|
144 | def set_nat(self, enable=True, persistent=False , eth=None): |
---|
145 | if eth == None: |
---|
146 | if self.external_interface == None: |
---|
147 | return {'status':False,'msg':'External interface is not defined'} |
---|
148 | else: |
---|
149 | eth = self.external_interface |
---|
150 | if persistent: |
---|
151 | try: |
---|
152 | if enable: |
---|
153 | self.interfaces.enable_nat([eth],'/usr/share/n4d-network/list_internal_interfaces') |
---|
154 | else: |
---|
155 | self.interfaces.disable_nat([eth]) |
---|
156 | except Exception as e: |
---|
157 | return {'status':False,'msg':e.message} |
---|
158 | self.interfaces.write_file(self.path_interfaces) |
---|
159 | script = ['enablenat'] |
---|
160 | if enable: |
---|
161 | script.append('A') |
---|
162 | else: |
---|
163 | script.append('D') |
---|
164 | script.append('/usr/share/n4d-network/list_internal_interfaces') |
---|
165 | script.append(eth) |
---|
166 | p = subprocess.Popen(script,stdout=subprocess.PIPE,stderr=subprocess.PIPE) |
---|
167 | result = p.communicate()[0] |
---|
168 | return {'status':True,'msg':'nat is set'} |
---|
169 | #def set_nat |
---|
170 | |
---|
171 | def get_nat(self): |
---|
172 | if self.external_interface == None: |
---|
173 | return {'status':False,'msg':'External interface is not defined'} |
---|
174 | p = subprocess.Popen(['iptables-save','-t','nat'],stdout=subprocess.PIPE,stdin=subprocess.PIPE) |
---|
175 | output = p.communicate()[0].split('\n') |
---|
176 | needle = "-A POSTROUTING -o "+self.external_interface+" -j MASQUERADE" |
---|
177 | if (needle in output): |
---|
178 | return {'status':True,'msg':'Nat is activated'} |
---|
179 | else: |
---|
180 | return {'status':False,'msg':'Nat is not activated'} |
---|
181 | #def get_nat |
---|
182 | |
---|
183 | def set_routing(self, enable=True, persistent=False): |
---|
184 | if enable: |
---|
185 | self.interfaces.enable_forwarding_ipv4(persistent) |
---|
186 | else: |
---|
187 | self.interfaces.disable_forwarding_ipv4(persistent) |
---|
188 | return {'status':True,'msg': 'routing set'} |
---|
189 | #def set_routing |
---|
190 | |
---|
191 | def get_routing(self): |
---|
192 | ret=self.interfaces.is_enable_forwarding_ipv4() |
---|
193 | if ret: |
---|
194 | msg="Routing is enabled" |
---|
195 | else: |
---|
196 | msg="Routing is disabled" |
---|
197 | return {'status':ret,'msg':msg} |
---|
198 | #def get_routing |
---|
199 | |
---|
200 | def get_nat_persistence(self): |
---|
201 | if self.external_interface != None: |
---|
202 | result = self.interfaces.get_nat_persistent(self.external_interface) |
---|
203 | status = 'enabled' if result else 'disabled' |
---|
204 | else: |
---|
205 | result = False |
---|
206 | status = 'disabled' |
---|
207 | return {'status': result,'msg' : 'Nat persistence is ' + status } |
---|
208 | #def get_nat_persistent |
---|
209 | |
---|
210 | def get_routing_persistence(self): |
---|
211 | result = self.interfaces.get_routing_persistent('ipv4') |
---|
212 | if result : |
---|
213 | return {'status':result,'msg':'Routing persistent is enabled'} |
---|
214 | else: |
---|
215 | return {'status':result,'msg':'Routing persistent is disabled'} |
---|
216 | #def get_routing_persistent |
---|
217 | |
---|
218 | def disable_network_manager(self): |
---|
219 | script = ['/usr/sbin/upstart-manager','network-manager'] |
---|
220 | p = subprocess.Popen(script,stdout=subprocess.PIPE,stderr=subprocess.PIPE) |
---|
221 | result = p.communicate()[0] |
---|
222 | script = ['stop','network-manager'] |
---|
223 | p = subprocess.Popen(script,stdout=subprocess.PIPE,stderr=subprocess.PIPE) |
---|
224 | result = p.communicate()[0] |
---|
225 | return {'status':True,'msg': 'Network Manager is disabled ^_^'} |
---|
226 | #def disable_network_manager |
---|
227 | |
---|
228 | def restart_interfaces(self): |
---|
229 | result = os.system('/etc/init.d/networking restart') |
---|
230 | |
---|
231 | for interface in lliurex.net.get_devices_info(): |
---|
232 | os.system("ifdown %s;ifup %s"%(interface["name"],interface["name"])) |
---|
233 | |
---|
234 | if (result == 0): |
---|
235 | return {'status':True,'msg':'network is restarted ok'} |
---|
236 | else: |
---|
237 | return {'status':False,'msg':'network has a problem. Please check file'} |
---|
238 | #def restart_interfaces |
---|
239 | |
---|
240 | def makedir(self,dir_path=None): |
---|
241 | |
---|
242 | if not os.path.isdir(dir_path): |
---|
243 | os.makedirs(dir_path) |
---|
244 | |
---|
245 | return [True] |
---|
246 | |
---|
247 | # def makedir |
---|
248 | |
---|
249 | |
---|
250 | def backup(self,dir_path="/backup"): |
---|
251 | |
---|
252 | |
---|
253 | try: |
---|
254 | |
---|
255 | self.makedir(dir_path) |
---|
256 | file_path=dir_path+"/"+get_backup_name("NetworkManager") |
---|
257 | |
---|
258 | |
---|
259 | tar=tarfile.open(file_path,"w:gz") |
---|
260 | |
---|
261 | for f in self.backup_files: |
---|
262 | if os.path.exists(f): |
---|
263 | tar.add(f) |
---|
264 | |
---|
265 | #for |
---|
266 | |
---|
267 | tar.close() |
---|
268 | print "Backup generated in %s" % file_path |
---|
269 | return [True,file_path] |
---|
270 | |
---|
271 | |
---|
272 | except Exception as e: |
---|
273 | print "Backup failed", e |
---|
274 | return [False,str(e)] |
---|
275 | |
---|
276 | #def backup |
---|
277 | |
---|
278 | def restore(self,file_path=None): |
---|
279 | |
---|
280 | |
---|
281 | |
---|
282 | #Ordeno de manera alfabetica el directorio y busco el fichero que tiene mi cadena |
---|
283 | if file_path==None: |
---|
284 | dir_path="/backup" |
---|
285 | for f in sorted(os.listdir(dir_path),reverse=True): |
---|
286 | |
---|
287 | if "NetworkManager" in f: |
---|
288 | file_path=dir_path+"/"+f |
---|
289 | break |
---|
290 | |
---|
291 | #Descomprimo el fichero y solo las cadenas que espero encontrar son las que restauro, reiniciando el servicio |
---|
292 | |
---|
293 | print "Trabajare con este fichero", file_path |
---|
294 | try: |
---|
295 | if os.path.exists(file_path): |
---|
296 | tmp_dir=tempfile.mkdtemp() |
---|
297 | tar=tarfile.open(file_path) |
---|
298 | tar.extractall(tmp_dir) |
---|
299 | tar.close |
---|
300 | for f in self.backup_files: |
---|
301 | tmp_path=tmp_dir+f |
---|
302 | if os.path.exists(tmp_path): |
---|
303 | shutil.copy(tmp_path,f) |
---|
304 | |
---|
305 | |
---|
306 | |
---|
307 | if os.path.exists(self.rules_file): |
---|
308 | os.remove(self.rules_file) |
---|
309 | |
---|
310 | os.system("/etc/init.d/networking restart") |
---|
311 | print "File is restored in %s" % self.backup_files |
---|
312 | |
---|
313 | return [True,""] |
---|
314 | |
---|
315 | |
---|
316 | except Exception as e: |
---|
317 | |
---|
318 | print "Restored failed", e |
---|
319 | return [False,str(e)] |
---|
320 | |
---|
321 | pass |
---|
322 | |
---|
323 | #def restore |
---|
324 | |
---|
325 | |
---|
326 | if __name__ == '__main__': |
---|
327 | e = NetworkManager() |
---|
328 | print e.get_interfaces() |
---|