Using an easier and safer way to update dhcpd configuration
This commit is contained in:
33
main.py
33
main.py
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import os
|
||||
import fileinput
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Annotated
|
||||
@@ -17,11 +18,11 @@ app = FastAPI()
|
||||
|
||||
security = HTTPBasic()
|
||||
|
||||
PATH = '/etc/'
|
||||
# PATH = './'
|
||||
USB_DHCPD_FILENAME = 'dhcpcd-backup.conf'
|
||||
ON_FILENAME = 'dhcpcd-backup-on.conf'
|
||||
OFF_FILENAME = 'dhcpcd-backup-off.conf'
|
||||
USB_DHCPD_FILENAME = '/etc/dhcpcd-backup.conf'
|
||||
#USB_DHCPD_FILENAME = './dhcpcd-backup.conf'
|
||||
AIR_INTERFACE_NAME = 'usb0'
|
||||
METRIC_ON = 50
|
||||
METRIC_OFF = 300
|
||||
|
||||
|
||||
class Config:
|
||||
@@ -92,8 +93,14 @@ async def set_status(username: Annotated[str, Depends(get_username)], status):
|
||||
|
||||
|
||||
def is_usb_on():
|
||||
real_filename = os.path.basename(os.path.realpath(PATH + USB_DHCPD_FILENAME))
|
||||
return real_filename == ON_FILENAME
|
||||
with open(USB_DHCPD_FILENAME, 'r') as dhcpd_file:
|
||||
right_interface = False
|
||||
for line in dhcpd_file:
|
||||
if line.startswith('interface'):
|
||||
right_interface = line.strip().split(' ')[-1] == AIR_INTERFACE_NAME
|
||||
|
||||
if right_interface and 'metric' in line:
|
||||
return line.strip().split(' ')[-1] == str(METRIC_ON)
|
||||
|
||||
|
||||
def switch_status(turn_on):
|
||||
@@ -106,9 +113,15 @@ def switch_status(turn_on):
|
||||
|
||||
|
||||
def update_dhcp_conf(turn_on):
|
||||
os.remove(PATH + USB_DHCPD_FILENAME)
|
||||
source_file = ON_FILENAME if turn_on else OFF_FILENAME
|
||||
os.symlink(PATH + source_file, PATH + USB_DHCPD_FILENAME)
|
||||
right_interface = False
|
||||
for line in fileinput.input(USB_DHCPD_FILENAME, inplace=True):
|
||||
if line.startswith('interface'):
|
||||
right_interface = line.strip().split(' ')[-1] == AIR_INTERFACE_NAME
|
||||
|
||||
if right_interface and 'metric' in line:
|
||||
print("\tmetric {}\n".format(METRIC_ON if turn_on else METRIC_OFF), end='')
|
||||
else:
|
||||
print(line, end='')
|
||||
|
||||
|
||||
def update_usb_modem(turn_on):
|
||||
|
||||
Reference in New Issue
Block a user