Configurar IP fija en Raspberry con Python
520 views
Creamos un archivo con los parámetros y lo llamamos red.txt:
[NETWORK] ipv4 = 192.168.1.213 gateway = 192.168.1.1 dns = 192.168.1.1 mask = 24
Necesitamos instalar la librería ConfigParser de Python:
pip install ConfigParser
El archivo python que leerá esos parámetros y cambiará la ip de nuestra Raspberry es:
#!/usr/bin/env python import re import ConfigParser config = ConfigParser.ConfigParser() config.read('red.txt') if config.has_section('NETWORK'): ip = config.get('NETWORK', 'ipv4') gateway = config.get('NETWORK', 'gateway') dns = config.get('NETWORK', 'dns') mask = config.get('NETWORK', 'mask') file_name = '/etc/dhcpcd.conf' with open(file_name, 'r') as f: file_text = f.read() if len(re.findall('inform', file_text)) == 0: # ip is not set (dhcp) newlines = [ 'interface eth0' + '\n', 'inform ' + ip + '\n', 'static routers=' + gateway + '\n', 'static domain_name_servers=' + dns + '\n' ] with open(file_name, 'a+') as f: f.writelines(newlines) else: # fixed ip. Change with new values newlines = [] with open(file_name) as f: lines = f.readlines() for l in lines: if re.findall('#', l): continue elif re.findall('inform [0-9.]*', l): newlines.append('inform ' + ip + '/' + mask + '\n') elif re.findall('static routers=', l): newlines.append('static routers=' + gateway + '\n') elif re.findall('static domain_name_servers=', l): newlines.append('static domain_name_servers=' + dns + '\n') else: newlines.append(l) with open(file_name, 'w') as n: n.writelines(newlines)
Ahora, ejecutamos nuestro archivo python y reiniciamos. Nuestra raspberry ya tendrá la nueva ip:
python cambiar_red.py sudo reboot
alert(«Loading…»);