change if names from enp*s0 to eth*

including all cfg files!
This commit is contained in:
2024-03-19 15:56:53 +01:00
parent ad130f16f4
commit 9c9719bff4
14 changed files with 88 additions and 69 deletions

View File

@ -17,10 +17,10 @@ content of the config files:
``` ```
[NETWORK] [NETWORK]
enp1s0=192.168.127.254 # leftmost socket: connect here a moxa with factory settings eth0=192.168.127.254 # leftmost socket: connect here a moxa with factory settings
enp2s0=192.168.2.2 # connected device will get this ip via DHCP eth1=192.168.2.2 # connected device will get this ip via DHCP
enp3s0=192.168.3.3 # or must be configured static to this IP eth2=192.168.3.3 # or must be configured static to this IP
enp4s0=dhcp # rightmost socket is the uplink eth3=dhcp # rightmost socket is the uplink
[ROUTER] [ROUTER]
3000=/dev/ttyUSB0 # routing 3000 to the internal serial port /dev/ttyUSB0 3000=/dev/ttyUSB0 # routing 3000 to the internal serial port /dev/ttyUSB0
@ -38,14 +38,12 @@ startup_text=startup...|HOST|ADDR # startup text, 3 lines separated with |
## network configuration ## network configuration
The example above fits the most cases. The example above fits the most cases.
Remark: as the control boxes (MLZ type) are labelled with 'eth0' etc., the names might be given in this form.
Internally the more modern names like 'enp1s0' are used.
Here a detailed description of possible settings: Here a detailed description of possible settings:
### fixed IP ### fixed IP
``` ```
enp2s0=192.168.3.5 eth1=192.168.3.5
``` ```
Configure the IP address of the connected device to get the specified IP via DHCP or Configure the IP address of the connected device to get the specified IP via DHCP or
configure the device to with this static IP. The last number must be within 1..254, configure the device to with this static IP. The last number must be within 1..254,
@ -53,7 +51,7 @@ the APU port itself will get 1 (or 2, if the specified IP is 1).
### custom network ### custom network
``` ```
enp3s0=192.168.3.1/24 # our ip address, the static address of the connected device must eth2=192.168.3.1/24 # our ip address, the static address of the connected device must
# be within 1-254 and not match our own # be within 1-254 and not match our own
``` ```
24 means 24 bit = 3 bytes network address. 24 means 24 bit = 3 bytes network address.
@ -63,20 +61,20 @@ Probably needed rarely.
### uplink via DHCP ### uplink via DHCP
``` ```
enp4s0=wan # or enp4s0=dhcp eth0=wan # or eth0=dhcp
``` ```
Uplink configured for DHCP in any network n.x.y.z with n < 192 Uplink configured for DHCP in any network n.x.y.z with n < 192
### customized uplink ### customized uplink
``` ```
enp1s0=wan,192.168.1.0/24 eth0=wan,192.168.1.0/24
``` ```
Add more networks to the allowed uplink range. More than one range is allowed, comma separated. Add more networks to the allowed uplink range. More than one range is allowed, comma separated.
Must not overlap networks specified for other ports! Must not overlap networks specified for other ports!
### disabled port ### disabled port
``` ```
enp3s0=off # disabled eth3=off # disabled
``` ```
## display ## display

View File

@ -1,9 +1,9 @@
[NETWORK] [NETWORK]
; please refer to README.md for help ; please refer to README.md for help
enp1s0=192.168.1.1/24 eth0=192.168.1.1/24
enp2s0=192.168.2.2/24 eth1=192.168.2.2/24
enp3s0=192.168.3.3/24 eth2=192.168.3.3/24
enp4s0=dhcp eth3=dhcp
[ROUTER] [ROUTER]
; please refer to README.md for help ; please refer to README.md for help

View File

@ -1,9 +1,9 @@
[NETWORK] [NETWORK]
; please refer to README.md for help ; please refer to README.md for help
enp1s0=192.168.127.254 eth0=192.168.127.254
enp2s0=192.168.2.1 eth1=192.168.2.1
enp3s0=192.168.3.5 eth2=192.168.3.5
enp4s0=dhcp eth3=dhcp
[ROUTER] [ROUTER]
; please refer to README.md for help ; please refer to README.md for help

View File

@ -1,9 +1,9 @@
[NETWORK] [NETWORK]
; please refer to README.md for help ; please refer to README.md for help
enp1s0=192.168.127.254 eth0=192.168.127.254
enp2s0=192.168.2.2 eth1=192.168.2.2
enp3s0=192.168.3.3 eth2=192.168.3.3
enp4s0=dhcp eth3=dhcp
[ROUTER] [ROUTER]
; please refer to README.md for help ; please refer to README.md for help

View File

@ -1,9 +1,9 @@
[NETWORK] [NETWORK]
; please refer to README.md for help ; please refer to README.md for help
enp1s0=wan,192.168.1.0/24 eth0=wan,192.168.1.0/24
enp2s0=192.168.2.2 eth1=192.168.2.2
enp3s0=192.168.3.3 eth2=192.168.3.3
enp4s0=192.168.127.254 eth3=192.168.127.254
[ROUTER] [ROUTER]
; please refer to README.md for help ; please refer to README.md for help

View File

@ -1,9 +1,9 @@
[NETWORK] [NETWORK]
; please refer to README.md for help ; please refer to README.md for help
enp1s0=dhcp eth0=dhcp
enp2s0=192.168.2.32 eth1=192.168.2.32
enp3s0=192.168.3.1 eth2=192.168.3.1
enp4s0=192.168.127.254 eth3=192.168.127.254
[ROUTER] [ROUTER]
; please refer to README.md for help ; please refer to README.md for help

View File

@ -1,8 +1,8 @@
[NETWORK] [NETWORK]
; please refer to README.md for help ; please refer to README.md for help
enp1s0=192.168.127.2/24 eth0=192.168.127.2/24
enp3s0=192.168.1.3/24 eth2=192.168.1.3/24
enp4s0=dhcp eth3=dhcp
[ROUTER] [ROUTER]
; please refer to README.md for help ; please refer to README.md for help

View File

@ -1,9 +1,9 @@
[NETWORK] [NETWORK]
; please refer to README.md for help ; please refer to README.md for help
enp1s0=192.168.127.254 eth0=192.168.127.254
enp2s0=192.168.12.2 eth1=192.168.12.2
enp3s0=192.168.13.3 eth2=192.168.13.3
enp4s0=wan,192.168.1.0/24 eth3=wan,192.168.1.0/24
[ROUTER] [ROUTER]
; please refer to README.md for help ; please refer to README.md for help

View File

@ -20,7 +20,7 @@ from glob import glob
from ipaddress import IPv4Interface from ipaddress import IPv4Interface
from configparser import ConfigParser from configparser import ConfigParser
from os.path import join, getmtime, exists, basename from os.path import join, getmtime, exists, basename
from utils import get_config, ifname_mapping from utils import get_config
if os.geteuid() != 0: if os.geteuid() != 0:
exit("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'. Exiting.") exit("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'. Exiting.")
@ -43,10 +43,10 @@ COMMENT = "; please refer to README.md for help"
CONFIG_TEMPLATE = f"""[NETWORK] CONFIG_TEMPLATE = f"""[NETWORK]
{COMMENT} {COMMENT}
enp1s0=192.168.127.254 eth0=192.168.127.254
enp2s0=192.168.2.2 eth1=192.168.2.2
enp3s0=192.168.3.3 eth2=192.168.3.3
enp4s0=dhcp eth3=dhcp
[ROUTER] [ROUTER]
{COMMENT} {COMMENT}
@ -55,10 +55,10 @@ enp4s0=dhcp
CONTROLBOX_TEMPLATE = f"""[NETWORK] CONTROLBOX_TEMPLATE = f"""[NETWORK]
{COMMENT} {COMMENT}
enp1s0=dhcp eth0=dhcp
enp2s0=192.168.1.1 eth1=192.168.1.1
enp3s0=192.168.2.2 eth2=192.168.2.2
enp4s0=192.168.3.3 eth3=192.168.3.3
[DISPLAY] [DISPLAY]
{COMMENT} {COMMENT}
@ -123,18 +123,23 @@ main_info = { # info to be determined depending on cfg
'hostname': socket.gethostname() # effective or given host name 'hostname': socket.gethostname() # effective or given host name
} }
change_if_names = False
for netif in os.scandir('/sys/class/net'): for netif in os.scandir('/sys/class/net'):
if netif.name != 'lo': # do not consider loopback interface if netif.name != 'lo': # do not consider loopback interface
with open(os.path.join(netif.path, 'address')) as f: with open(os.path.join(netif.path, 'address')) as f:
addr = f.read().strip().lower() addr = f.read().strip().lower()
net_addr[netif.name] = addr n = netif.name
if n.startswith('enp'):
change_if_names = True
n = f'eth{int(n[3]) - 1}'
net_addr[n] = addr
sorted_if = sorted(net_addr) sorted_if = sorted(net_addr)
boxaddr = net_addr[sorted_if[0]] boxaddr = net_addr[sorted_if[0]]
boxid = int(''.join(boxaddr.split(':')[-3:]), 16) & 0xffffff boxid = int(''.join(boxaddr.split(':')[-3:]), 16) & 0xffffff
boxtype = BOX_TYPES.get(boxaddr[:8]) boxtype = BOX_TYPES.get(boxaddr[:8])
if boxtype != 'apu':
ifname_mapping.clear()
TO_SYSTEM = f'{TOOLS}/to_{boxtype}' TO_SYSTEM = f'{TOOLS}/to_{boxtype}'
if not exists(TO_SYSTEM): if not exists(TO_SYSTEM):
TO_SYSTEM = f'{TOOLS}/to_system' TO_SYSTEM = f'{TOOLS}/to_system'
@ -295,7 +300,6 @@ def create_if(name, cfg):
else: else:
cfgip = IPv4Interface(cfg) cfgip = IPv4Interface(cfg)
network = cfgip.network network = cfgip.network
print('N', network, network.prefixlen)
if network.prefixlen == 32: # or no prefix specified if network.prefixlen == 32: # or no prefix specified
otherip = IPv4Interface('%s/24' % cfgip.ip) otherip = IPv4Interface('%s/24' % cfgip.ip)
network = otherip.network network = otherip.network
@ -410,7 +414,7 @@ def handle_config():
cfgfiles.append(file) cfgfiles.append(file)
if boxtype == 'apu': if boxtype == 'apu':
for i in [1, 2, 3]: for i in [1, 2, 3]:
bad = glob(CFGPATH % ('*', apuid+i)) bad = glob(CFGPATH % ('*', boxid+i))
if bad: if bad:
print('cfg files found with bad apu id (use net addr of leftmost plug)') print('cfg files found with bad apu id (use net addr of leftmost plug)')
print(bad) print(bad)
@ -460,6 +464,10 @@ def handle_config():
config = get_config() config = get_config()
try: try:
netcfg = config['NETWORK'] netcfg = config['NETWORK']
for name in netcfg:
if name not in net_addr:
print(f'{name} is not a valid network interface name')
raise RuntimeError('network interface name system does not match')
for ifname in net_addr: for ifname in net_addr:
content = create_if(ifname, netcfg.get(ifname, 'off')) content = create_if(ifname, netcfg.get(ifname, 'off'))
# content = '\n'.join('%s=%s' % kv for kv in content.items()) # content = '\n'.join('%s=%s' % kv for kv in content.items())
@ -469,7 +477,6 @@ def handle_config():
show.dirty = True show.dirty = True
to_start[ifname] = 'if_restart' to_start[ifname] = 'if_restart'
if dhcp_server_cfg: if dhcp_server_cfg:
print(dhcp_server_cfg)
content = [DHCP_HEADER] content = [DHCP_HEADER]
for subnet, rangelist in dhcp_server_cfg: for subnet, rangelist in dhcp_server_cfg:
try: try:
@ -565,6 +572,18 @@ def handle_config():
if action == 'restart': if action == 'restart':
unix_cmd('systemctl restart %s' % service) unix_cmd('systemctl restart %s' % service)
unix_cmd('systemctl enable %s' % service) unix_cmd('systemctl enable %s' % service)
if change_if_names:
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 newcontent:
write_when_new('/etc/default/grub', newcontent)
unix_cmd('update-grub')
result = [f'config file:\n {cfgfile}'] result = [f'config file:\n {cfgfile}']
for section, section_dict in config.items(): for section, section_dict in config.items():
result.append(section) result.append(section)

View File

@ -78,7 +78,7 @@ for arg in sys.argv[1:]:
log = Log(loglev) log = Log(loglev)
FILTER = "iptables -i enp4s0 -p tcp -m tcp --dport %d -j ACCEPT" FILTER = "iptables -i eth0 -p tcp -m tcp --dport %d -j ACCEPT"
BASIC = """ BASIC = """
iptables -P INPUT %(accept)s iptables -P INPUT %(accept)s

View File

@ -1,4 +1,4 @@
ETHNAME=$(cat /sys/class/net/enp1s0/address) ETHNAME=$(cat /sys/class/net/eth0/address)
ETHNAME=${ETHNAME//:/} ETHNAME=${ETHNAME//:/}
APUID=${ETHNAME: -6} APUID=${ETHNAME: -6}
FOUND="$(shopt -s nullglob; echo /home/l_samenv/boxtools/cfg/*_$APUID.cfg)" FOUND="$(shopt -s nullglob; echo /home/l_samenv/boxtools/cfg/*_$APUID.cfg)"

View File

@ -14,5 +14,5 @@
# On what interfaces should the DHCP server (dhcpd) serve DHCP requests? # On what interfaces should the DHCP server (dhcpd) serve DHCP requests?
# Separate multiple interfaces with spaces, e.g. "eth0 eth1". # Separate multiple interfaces with spaces, e.g. "eth0 eth1".
INTERFACESv4="enp2s0 enp3s0 enp4s0" INTERFACESv4="eth1 eth2 eth3"
INTERFACESv6="" INTERFACESv6=""

View File

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

View File

@ -6,14 +6,6 @@ from configparser import ConfigParser
from netifaces import interfaces, ifaddresses, gateways, AF_INET, AF_LINK from netifaces import interfaces, ifaddresses, gateways, AF_INET, AF_LINK
ifname_mapping = {
'eth0': 'enp1s0',
'eth1': 'enp2s0',
'eth2': 'enp3s0',
'eth3': 'enp4s0',
}
if os.geteuid(): if os.geteuid():
def sudo(cmd): def sudo(cmd):
os.system(f'sudo {cmd}') os.system(f'sudo {cmd}')
@ -30,6 +22,19 @@ def get_config(section=None):
""" """
parser = ConfigParser() parser = ConfigParser()
cfgfiles = glob('/home/l_samenv/boxtools/cfg/%s_*.cfg' % socket.gethostname()) cfgfiles = glob('/home/l_samenv/boxtools/cfg/%s_*.cfg' % socket.gethostname())
if not cfgfiles:
# look by id
boxid = None
for ifname in ('enp1s0', 'eth0'):
try:
with open(f'/sys/class/net/{ifname}/address') as f:
addr = f.read().strip().lower()
except FileNotFoundError:
continue
boxid = int(''.join(addr.split(':')[-3:]), 16) & 0xffffff
break
if boxid:
cfgfiles = glob('/home/l_samenv/boxtools/cfg/*_%6.6x.cfg' % boxid)
if len(cfgfiles) != 1: if len(cfgfiles) != 1:
raise ValueError('there must be one and only one single cfgfile %r' % cfgfiles) raise ValueError('there must be one and only one single cfgfile %r' % cfgfiles)
parser.read(cfgfiles[0]) parser.read(cfgfiles[0])
@ -37,9 +42,6 @@ def get_config(section=None):
result = {k: dict(parser[k]) for k in ([section] if section else parser.sections())} result = {k: dict(parser[k]) for k in ([section] if section else parser.sections())}
except KeyError: except KeyError:
return {} return {}
network = result.get('NETWORK', {})
for name in list(network):
network[ifname_mapping.get(name, name)] = network.pop(name)
if section: if section:
return result[section] return result[section]
return result return result