fix boxtools for rpi

- remove to_cm4
- create replace_in_file
This commit is contained in:
l_samenv
2024-03-20 12:01:50 +01:00
parent 26122843b2
commit 5dc4f8a984
7 changed files with 62 additions and 37 deletions

View File

@ -0,0 +1,7 @@
[NETWORK]
eth0=wan
eth1=192.168.127.2
[ROUTER]
8080:192.168.127.2:80

View File

@ -13,6 +13,7 @@ import os
import filecmp
import shutil
import serial
import re
import types
import socket
from subprocess import Popen, PIPE
@ -111,9 +112,7 @@ pip_requirements = {
box = BoxInfo()
dhcp_server_cfg = []
TO_SYSTEM = f'{TOOLS}/to_{box.typ}'
if not exists(TO_SYSTEM):
TO_SYSTEM = f'{TOOLS}/to_system'
TO_SYSTEM = f'{TOOLS}/to_system'
os.chdir(TO_SYSTEM)
@ -252,6 +251,42 @@ def write_when_new(filename, content, ignore_reduction=False):
return content
def replace_in_file(filename, pat, repl):
"""find pattern <prev> in content of filename
find regexp pattern <pat> in content of file
- if it does not match exactly once, an error is raised
- exchange group 1 by repl
- return True when result is changed, or False when not
doit determines, whether the file is really changed
"""
with open(filename) as f:
content = f.read()
success = []
def fun(match, count=[]):
if success:
raise ValueError(f'{pat} matches multiple times in {filename}')
part = match.group(0)
match = match.re.match(part)
fr, to = match.span(1)
result = part[:fr] + repl + part[to:]
if result != part:
print(f'in {filename} replace {part} -> {result}')
success.append(result != part)
return result
newcontent = re.sub(pat, fun, content)
if not success:
raise ValueError(f'{pat} not in {filename}')
write_when_new(filename, newcontent)
return success[0]
def create_if(name, cfg):
if cfg == 'off':
result = None
@ -379,6 +414,7 @@ class Do(Walker):
def handle_config():
dhcp_server_cfg.clear()
config = box.read_config()
cfgfile = box.cfgfile
newhostname = box.hostname
if not cfgfile:
@ -413,7 +449,7 @@ def handle_config():
if cfgfile:
print('replace host name %r by %r' % (box.hostname, newhostname))
show.dirty = True
config = box.read_config()
config = box.read_config()
box.hostname = newhostname
if cfgfile is None:
return False
@ -452,6 +488,8 @@ def handle_config():
print('change dhcpd.conf')
to_start['isc-dhcp-server'] = 'restart'
show.dirty = True
replace_in_file('/etc/default/isc-dhcp-server',
r'INTERFACESv4="(.*)"', ' '.join([n for n in box.macaddr if n != box.main_if]))
elif doit:
unix_cmd('systemctl stop isc-dhcp-server')
unix_cmd('systemctl disable isc-dhcp-server')
@ -532,14 +570,9 @@ def handle_config():
if box.change_if_names:
print('interface name system has to be changed from enp*s0 to eth*')
with open('/etc/default/grub') as f:
content = f.read()
prev = 'GRUB_CMDLINE_LINUX_DEFAULT="quiet"'
repl = 'GRUB_CMDLINE_LINUX_DEFAULT="quiet net.ifnames=0"'
newcontent = content.replace(prev, repl)
if repl not in content:
write_when_new('/etc/default/grub', newcontent)
if replace_in_file('/etc/default/grub',
r'GRUB_CMDLINE_LINUX_DEFAULT="quiet(.*)"',
' net.ifnames=0"'):
unix_cmd('update-grub')
result = [f'config file:\n {cfgfile}']

View File

@ -9,7 +9,7 @@ from glob import glob
from select import select
from serial import serial_for_url
from subprocess import Popen, PIPE, check_output, call, DEVNULL
from utils import get_config
from utils import BoxInfo
FIREWALL_CONF = '/etc/nftables.conf'
@ -478,6 +478,6 @@ class Service:
if __name__ == '__main__':
routercfg = get_config('ROUTER')
routercfg = BoxInfo().read_config('ROUTER')
if routercfg:
Service.run(routercfg)

View File

@ -1,18 +0,0 @@
# Defaults for isc-dhcp-server (sourced by /etc/init.d/isc-dhcp-server)
# Path to dhcpd's config file (default: /etc/dhcp/dhcpd.conf).
#DHCPDv4_CONF=/etc/dhcp/dhcpd.conf
#DHCPDv6_CONF=/etc/dhcp/dhcpd6.conf
# Path to dhcpd's PID file (default: /var/run/dhcpd.pid).
#DHCPDv4_PID=/var/run/dhcpd.pid
#DHCPDv6_PID=/var/run/dhcpd6.pid
# Additional options to start dhcpd with.
# Don't use options -cf or -pf here; use DHCPD_CONF/ DHCPD_PID instead
#OPTIONS=""
# On what interfaces should the DHCP server (dhcpd) serve DHCP requests?
# Separate multiple interfaces with spaces, e.g. "eth0 eth1".
INTERFACESv4="eth1 eth2 eth3"
INTERFACESv6=""

View File

@ -1,7 +1,7 @@
export EDITOR=nano
echo "-----------------------------------------------------"
echo "Welcome to $HOSTNAME $(hostname -I)"
echo "ethernet addr $(cat /sys/class/net/eth0/address) .. $(cat /sys/class/net/eth3/address)"
echo "ethernet addr $(cat /sys/class/net/eth0/address)"
function service_status () {
for name in $@; do \
enabled=$(systemctl is-enabled ${name} 2> /dev/null) && \

View File

@ -5,7 +5,7 @@ Before=network.pre-target
[Service]
Type=oneshot
ExecStart = /usr/bin/bash /home/l_samenv/boxtools/sethostname.sh
ExecStart = /usr/bin/bash /home/l_samenv/boxtools/rpihostname.sh
RemainAfterExit=yes
[Install]

View File

@ -39,7 +39,6 @@ class BoxInfo:
if ifname.startswith('enp'):
self.change_if_names = True
ifname = f'eth{int(ifname[3]) - 1}'
print(ifname)
with open(ifdev) as f:
self.macaddr[ifname] = addr = f.read().strip().lower()
if ifname in ('eth0', 'enp1s0'):
@ -50,7 +49,7 @@ class BoxInfo:
def get_macaddr(self):
return self.macaddr.get(self.main_if)
def read_config(self):
def read_config(self, section=None):
cfgfiles = glob(self.CFGPATH % ('*', self.id))
if len(cfgfiles) != 1:
raise ValueError('there must be one and only one single cfgfile %r' % cfgfiles)
@ -58,6 +57,10 @@ class BoxInfo:
self.cfgfile = cfgfiles[0]
parser = ConfigParser()
parser.read(self.cfgfile)
if section:
if section in parser.sections():
return dict(parser[section])
return None
return {k: dict(parser[k]) for k in parser.sections()}
@ -78,7 +81,7 @@ class MainIf:
prev_ip = None
def __init__(self):
netcfg = get_config('NETWORK')
netcfg = BoxInfo().read_config('NETWORK')
for name, key in netcfg.items():
if key.startswith(('dhcp', 'wan')):
self.name = name