Quantcast
Viewing all articles
Browse latest Browse all 4325

Python • Re: super user command from Python script

You could replace the running process by a new process, recalling the python program with root. When the work is done, the code could drop the privileges. The sudo command creates some environment variables, and SUDO_UID is the interesting one. So you can use this variable, to change the current UID from 0 to the UID of the user, who has run the program.

Code:

import osimport sysfrom contextlib import contextmanager@contextmanagerdef run_as_root():    if os.getuid() != 0:        print("Replacing the current process with a new process")        os.execvp("sudo", ["sudo", sys.executable, *sys.argv])    yield    # switching back to old user id    # sudo creates environment variables    # where SUDO_UID is the user, who has calle sudo    # the following function set the old user id    # this works only, if you have the permission (root)    os.setuid(int(os.environ["SUDO_UID"]))print("Running before contextmanager as uid", os.getuid())# this here will rerun the whole program as rootwith run_as_root():    print("Running as uid inside the context manager", os.getuid())    try:        with open("/sys/module/imx296/parameters/trigger_mode", "w") as fd:            fd.write("1")    except FileNotFoundError:        print("The module imx296 is currently not loaded")# here the old UID is set, so the programm dropped the priviledges and# is not able to regain itprint("Running outside the contextmanager as uid", os.getuid())

Statistics: Posted by DeaD_EyE — Sun Jun 16, 2024 11:14 am



Viewing all articles
Browse latest Browse all 4325

Trending Articles