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
|
#!/usr/bin/env python
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
import fileinput
|
||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
@@ -17,11 +18,11 @@ app = FastAPI()
|
|||||||
|
|
||||||
security = HTTPBasic()
|
security = HTTPBasic()
|
||||||
|
|
||||||
PATH = '/etc/'
|
USB_DHCPD_FILENAME = '/etc/dhcpcd-backup.conf'
|
||||||
# PATH = './'
|
#USB_DHCPD_FILENAME = './dhcpcd-backup.conf'
|
||||||
USB_DHCPD_FILENAME = 'dhcpcd-backup.conf'
|
AIR_INTERFACE_NAME = 'usb0'
|
||||||
ON_FILENAME = 'dhcpcd-backup-on.conf'
|
METRIC_ON = 50
|
||||||
OFF_FILENAME = 'dhcpcd-backup-off.conf'
|
METRIC_OFF = 300
|
||||||
|
|
||||||
|
|
||||||
class Config:
|
class Config:
|
||||||
@@ -92,8 +93,14 @@ async def set_status(username: Annotated[str, Depends(get_username)], status):
|
|||||||
|
|
||||||
|
|
||||||
def is_usb_on():
|
def is_usb_on():
|
||||||
real_filename = os.path.basename(os.path.realpath(PATH + USB_DHCPD_FILENAME))
|
with open(USB_DHCPD_FILENAME, 'r') as dhcpd_file:
|
||||||
return real_filename == ON_FILENAME
|
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):
|
def switch_status(turn_on):
|
||||||
@@ -106,9 +113,15 @@ def switch_status(turn_on):
|
|||||||
|
|
||||||
|
|
||||||
def update_dhcp_conf(turn_on):
|
def update_dhcp_conf(turn_on):
|
||||||
os.remove(PATH + USB_DHCPD_FILENAME)
|
right_interface = False
|
||||||
source_file = ON_FILENAME if turn_on else OFF_FILENAME
|
for line in fileinput.input(USB_DHCPD_FILENAME, inplace=True):
|
||||||
os.symlink(PATH + source_file, PATH + USB_DHCPD_FILENAME)
|
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):
|
def update_usb_modem(turn_on):
|
||||||
|
|||||||
Reference in New Issue
Block a user