mirror of
https://github.com/kernelkit/infix.git
synced 2026-08-03 06:13:02 +02:00
test: new infamy DHCP server class
Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
This commit is contained in:
committed by
Mattias Walström
parent
6244777f8e
commit
5056424867
@@ -0,0 +1,55 @@
|
||||
"""Start a DHCP server in the background"""
|
||||
import os
|
||||
import subprocess
|
||||
import ipaddress
|
||||
|
||||
class Server:
|
||||
config_file = '/tmp/udhcpd.conf'
|
||||
leases_file = '/tmp/udhcpd.leases'
|
||||
|
||||
def __init__(self, netns, subnet='192.168.0.0', netmask='255.255.255.0', ip='192.168.0.20'):
|
||||
self.process = None
|
||||
self.netns = netns
|
||||
self._create_files(subnet, netmask, ip)
|
||||
|
||||
def __del__(self):
|
||||
print(self.config_file)
|
||||
#os.unlink(self.config_file)
|
||||
#os.unlink(self.leases_file)
|
||||
|
||||
def __enter__(self):
|
||||
self.start()
|
||||
|
||||
def __exit__(self, _, __, ___):
|
||||
self.stop()
|
||||
|
||||
def _create_files(self, subnet, netmask, ip):
|
||||
f = open(self.leases_file, "w")
|
||||
f.close()
|
||||
|
||||
with open(self.config_file, 'w') as f:
|
||||
f.write(f'''# Generated by Infamy DHCP
|
||||
lease_file {self.leases_file}
|
||||
interface iface
|
||||
start {ip}
|
||||
end {ip}
|
||||
max_leases 1
|
||||
option subnet {netmask}
|
||||
option lease 864000
|
||||
''')
|
||||
|
||||
def get_pid(self):
|
||||
return self.process.pid
|
||||
|
||||
def start(self):
|
||||
if not os.path.exists(self.config_file):
|
||||
raise Exception("Config file does not exist. Please create it first.")
|
||||
cmd = f"udhcpd -f {self.config_file}"
|
||||
print(f"Starting: {cmd}")
|
||||
self.process = self.netns.popen(cmd.split(" "))
|
||||
|
||||
def stop(self):
|
||||
if self.process:
|
||||
self.process.terminate()
|
||||
self.process.wait()
|
||||
self.process = None
|
||||
Reference in New Issue
Block a user