ifcfg scripts are now created from scratch

- ifcfg script do not contain UUID any more
This commit is contained in:
2021-04-08 07:02:57 +02:00
parent 53af769c3f
commit 2fadf63da8
8 changed files with 78 additions and 68 deletions

View File

@ -17,6 +17,28 @@ os.chdir('to_system')
DEL = '__to_delete__' DEL = '__to_delete__'
CFGPATH = '/root/aputools/servercfg/%s.cfg' CFGPATH = '/root/aputools/servercfg/%s.cfg'
def create_if(name, mac, cfg):
result=dict(TYPE='Ethernet', NAME=name, DEVICE=name,
BOOTPROTO='none', ONBOOT='yes')
if cfg == 'off':
result['ONBOOT']='no'
elif cfg == 'dhcp':
result['BOOTPROTO']='dhcp'
else:
interface = IPv4Interface(cfg)
if '/' not in cfg:
if interface < IPv4Interface('128.0.0.0'):
cfg += '/8'
elif interface < IPv4Interface('192.0.0.0'):
cfg += '/16'
else:
cfg += '/24'
interface = IPv4Interface(cfg)
result['IPADDR'], result['NETMASK'] = interface.with_netmask.split('/')
_, result['PREFIX'] = interface.with_prefixlen.split('/')
return result
def walk(action): def walk(action):
for dirpath, _, files in os.walk('.'): for dirpath, _, files in os.walk('.'):
syspath = dirpath[1:] # remove leading '.' syspath = dirpath[1:] # remove leading '.'
@ -83,11 +105,15 @@ class Do:
os.remove(join(self.syspath, file)) os.remove(join(self.syspath, file))
IFNAMES = ['enp%ds0' % i for i in range(1,5)]
def network(doit): def network(doit):
result = None result = True
dirty = None netaddr_dict = {}
with open('/sys/class/net/enp1s0/address') as f: for ifname in IFNAMES:
netaddr = f.read().strip().lower() with open('/sys/class/net/%s/address' % ifname) as f:
netaddr_dict[ifname] = f.read().strip().lower()
netaddr = netaddr_dict[IFNAMES[0]]
action = 'doit' if doit else 'check' action = 'doit' if doit else 'check'
addrdict = {} addrdict = {}
for cfgfile in glob(CFGPATH % '*'): for cfgfile in glob(CFGPATH % '*'):
@ -99,15 +125,14 @@ def network(doit):
print(cfgfile) print(cfgfile)
print(addrdict[address]) print(addrdict[address])
print('ERROR: duplicate address %s in above files' % address) print('ERROR: duplicate address %s in above files' % address)
result = 'failed'
addrdict[address] = cfgfile addrdict[address] = cfgfile
except Exception as e: except Exception as e:
print('ERROR: can not read %s: %r' % (cfgfile, e)) print('ERROR: can not read %s: %r' % (cfgfile, e))
result = 'failed' result = False
cfgfile = addrdict.get(netaddr) cfgfile = addrdict.get(netaddr)
if cfgfile is None: if cfgfile is None:
print('can not find cfg file for %s' % netaddr) print('can not find cfg file for %s' % netaddr)
result = 'failed' result = False
for ntry in range(1 + bool(doit)): for ntry in range(1 + bool(doit)):
with open('/etc/hostname') as f: with open('/etc/hostname') as f:
hostname = f.read().strip() hostname = f.read().strip()
@ -118,12 +143,11 @@ def network(doit):
os.system('sh sethostname.sh') os.system('sh sethostname.sh')
else: else:
print('ERROR: can not set host name') print('ERROR: can not set host name')
result = 'failed' result = False
else: else:
print('host name does not match') print('host name does not match')
dirty = 'dirty'
break break
if result: if not result:
return False return False
ifname = '' ifname = ''
parser = ConfigParser() parser = ConfigParser()
@ -132,67 +156,24 @@ def network(doit):
network = dict(parser['NETWORK']) network = dict(parser['NETWORK'])
address = network.pop('address', None) address = network.pop('address', None)
main = None main = None
for ifname, value in network.items(): for ifname in IFNAMES:
try: content = create_if(ifname, netaddr_dict[ifname],
with open('/etc/sysconfig/network-scripts/ifcfg-%s' % ifname) as f: network.get(ifname, 'off'))
original = f.read().strip().split('\n') with open('etc/sysconfig/network-scripts/ifcfg-%s' % ifname, 'w') as f:
except FileNotFoundError: f.write('\n'.join('%s=%s' % kv for kv in content.items())+ '\n')
raise ValueError('unknown interface %s' % ifname)
content = {}
for line in original:
key, _, val = line.strip().partition('=')
if val:
content[key] = val
if content['NAME'] != ifname:
print('ERROR: name %s does not match' % content['NAME'])
result = 'failed'
original = dict(content)
if value == 'dhcp':
if main:
print('ERROR: only one interface with DHCP allowed')
result = 'failed'
main = ifname
content.pop('IPADDR', None)
content['ONBOOT'] = 'yes'
content['BOOTPROTO'] = 'dhcp'
else:
interface = IPv4Interface(value)
if '/' not in value:
if interface < IPv4Interface('128.0.0.0'):
value += '/8'
elif interface < IPv4Interface('192.0.0.0'):
value += '/16'
else:
value += '/24'
interface = IPv4Interface(value)
content['IPADDR'], content['NETMASK'] = interface.with_netmask.split('/')
_, content['PREFIX'] = interface.with_prefixlen.split('/')
content['ONBOOT'] = 'yes'
content['BOOTPROTO'] = 'none'
if content != original:
if doit:
with open('/etc/sysconfig/network-scripts/ifcfg-%s' % ifname, 'w') as f:
f.write('%s\n' % '\n'.join('%s=%s' % kv for kv in content.items()))
else:
dirty = 'dirty'
print('%s changed:' % ifname)
diff = dict(content)
diff.update({k: '' for k in original if k not in diff})
print(' %s' % ', '.join('%s=%s' % (k, v) for k, v in diff.items() if v != original.get(k)))
except Exception as e: except Exception as e:
print('ERROR: can not handle %s %s: %r' % (hostname, ifname, e)) print('ERROR: can not handle %s %s: %r' % (hostname, ifname, e))
result = 'failed' result = False
return result or dirty return result
print('---') print('---')
show = Show() show = Show()
walk(show)
result = network(False) result = network(False)
walk(show)
if result == 'failed': if not result:
print('fix first above errors') print('fix first above errors')
elif result == 'dirty' or show.dirty: elif show.dirty:
print('---') print('---')
answer = input('do above? ') answer = input('do above? ')
if answer.lower().startswith('y'): if answer.lower().startswith('y'):

View File

@ -1,5 +1,5 @@
[NETWORK] [NETWORK]
address=00:0d:b9:5a:58:e4 address=00:0d:b9:5a:4c:90
enp1s0=dhcp enp1s0=dhcp
enp2s0=192.168.2.2/24 enp2s0=192.168.2.2/24
enp3s0=192.168.2.3/24 enp3s0=192.168.2.3/24

View File

@ -1,9 +1,9 @@
[NETWORK] [NETWORK]
address=00:0d:b9:5a:4c:90 address=00:0d:b9:5a:58:e4
enp1s0=dhcp enp1s0=192.168.2.1/24
enp2s0=192.168.2.2/24 enp2s0=192.168.2.2/24
enp3s0=192.168.2.3/24 enp3s0=192.168.2.3/24
enp4s0=192.168.127.4/24 enp4s0=dhcp
[ROUTER] [ROUTER]
3000=/dev/ttyUSB0 3000=/dev/ttyUSB0

View File

@ -1,3 +1,3 @@
echo "Welcome to $HOSTNAME $(hostname -I)" echo "Welcome to $HOSTNAME $(hostname -I)"
echo "$(cat /sys/class/net/enp1s0/address)" echo "$(cat /sys/class/net/enp4s0/address)"
export EDITOR=nano export EDITOR=nano

View File

@ -0,0 +1,8 @@
TYPE=Ethernet
NAME=enp1s0
DEVICE=enp1s0
BOOTPROTO=none
ONBOOT=yes
IPADDR=192.168.2.1
NETMASK=255.255.255.0
PREFIX=24

View File

@ -0,0 +1,8 @@
TYPE=Ethernet
NAME=enp2s0
DEVICE=enp2s0
BOOTPROTO=none
ONBOOT=yes
IPADDR=192.168.2.2
NETMASK=255.255.255.0
PREFIX=24

View File

@ -0,0 +1,8 @@
TYPE=Ethernet
NAME=enp3s0
DEVICE=enp3s0
BOOTPROTO=none
ONBOOT=yes
IPADDR=192.168.2.3
NETMASK=255.255.255.0
PREFIX=24

View File

@ -0,0 +1,5 @@
TYPE=Ethernet
NAME=enp4s0
DEVICE=enp4s0
BOOTPROTO=dhcp
ONBOOT=yes