Actualités
| Parse Debian/Ubuntu network config |
|---|
Ecrit par Poil | 2013-02-28 15:08:27 |
Récemment au boulot j'ai eu besoin d'éditer des configurations debian/ubuntu réseau. from fabric.operations import put, sudo, local, run
import os.path
import re
def parse_debconf_network():
""" Parse /etc/network/interfaces
return a dictionnary of all elements
"""
iface = {}
output = run('cat /etc/network/interfaces')
for line in output.split('/n'):
if re.match(r'^(manual|auto)', line.strip()):
ifacenum = re.split('/s+', line.strip())[1]
ifacemode = re.split('/s+', line.strip())[0]
iface[ifacenum] = {'ifacemode': ifacemode}
elif not re.match(r'^#', line.strip()):
key = re.split('/s+', line.strip())[0]
if re.match(r'pre|post', key):
if not iface[ifacenum].get(key, False):
iface[ifacenum][key] = []
iface[ifacenum][key].append(' '.join(re.split('/s+', line.strip())[1:]))
elif key != '':
value = ' '.join(re.split('/s+', line.strip())[1:])
iface[ifacenum][key] = value
return iface
def generate_debconf_network(iface, remote_file='/etc/network/interfaces.new'):
""" Generate a debian like network configuration file from a dictionnary (generated by parse_debconf_network)
@param iface: The dictionnary
@param remote_file: Output file
"""
local_file = '/var/tmp/interfaces'
f = open(local_file, 'w+')
for cur_if, conf in iter(sorted(iface.iteritems())):
f.write(conf['ifacemode'] + ' ' + cur_if + '/n')
f.write('iface ' + conf['iface'] + '/n')
for key, elem in iter(sorted(conf.iteritems())):
if key != 'iface' and key != 'ifacemode':
if type(elem) == list:
for subelem in elem:
f.write('/t' + key + ' ' + subelem + '/n')
else:
f.write('/t' + key + ' ' + elem + '/n')
f.write('/n')
f.close()
put(local_file, remote_file, use_sudo=True)
sudo('chown root.root ' + remote_file)
local('rm ' + local_file)
@task
def toto():
myconf = parse_debconf_network()
# On modifie le netmask d'eth0
myconf['eth0']['netmask'] = '255.255.254.0'
# On ajoute une route sur eth1
myconf['eth1']['post-up'].append('ip route add 192.168.229.0/24 via 192.168.131.1 || true')
myconf['eth1']['pre-down'].append('ip route del 192.168.229.0/24 via 192.168.131.1 || true')
generate_debconf_network(myconf)
|
Commentaires
| Aucun commentaire |
Développé par Poil - Graphismes de DarkDaV - Icônes sous licence Creative Commons (famfam, nuovo ...)
Ecrit par Poil |
2013-02-28 15:08:27