Consider the following python code which is split between two files. The main module is trying to run the dhcp with elevated privileges. I am making use of elevate to do the elevation.
# main.py
import subprocess, time
if __name__ == '__main__':
print("main started")
p = subprocess.Popen(['python', 'dhcp.py'])
time.sleep(6)
p.terminate()
p.wait()
# dhcp.py
from elevate import elevate
elevate()
print("I am an elevated process")
My aim is to run the dhcp file (a dhcp server) without restarting my main process AND have some control over the dhcp server (terminate it at some point; ideally, gracefully). If I do not use subprocess, then the elevation will restart main such that I see main started printed twice.
My questions:
- I understand that elevation in both Windows and Linux has to be at the process level (i.e. you cannot just invoke a single function with elevated privileges) - hence why
main startedis seen twice when not using subprocess. Is this understanding correct? - As the code is written, the
dhcpwill not be terminated by main becauseelevatehas restarted thedhcpprocess which meanspis no longer referencing the correct process (at least, this is my understanding). Is there some way to rundhcpwithout restartingmainprocess and still retain control over thedhcpprocess? - I also tried multiprocessing to start the
dhcp(target was a function indhcp- not shown) but in that case I seemain startedbeing printed again after the elevation (i.e.mainis restarted) which was a surprise as I thought it would be a separate child process. Why would this not be separate? And, my experiments show that this also suffers from the same issue as #2 - i.e. cannot terminate the child process. It seems to only stop when themainprocess dies.
ETA: tests run on Windows 10 but I am looking to be able to do this on both Windows and Linux.