has anyone figured out how to safely do a setuid root script in Python on Linux? normally this would require a compiled (usually in C or C++) executable that carefully finds the script to execute and runs it. then you (the admin with root or sudo powers) would set the compiled executable to be suid root, and runs the script with the effective uid it has (such as root). i have written one of these in C when i needed to make some bash scripts run suid root. i could use it for Python if i can find it (from about 24 years ago). i am just wondering if anyone has solved this another way. i have thought about this at times for a few years and imagined that this could be solved by the interpreter detecting this configuration and handling it itself.
With os.execvp you can run python again with sudo.
I have a example at home. I'll update my post.
It's also an example for windows included.
import os
import sys
import subprocess
import platform
def windows_elevation():
import ctypes
is_admin = bool(ctypes.windll.shell32.IsUserAnAdmin())
if not is_admin:
ctypes.windll.shell32.ShellExecuteW(
None, 'runas',
sys.executable,
sys.argv[0], None, 1)
sys.exit(0)
def linux_elevation():
exe = sys.executable
cmd = sys.argv
uid = os.getuid()
if uid != 0:
#print('No user root, elevating with sudo')
os.execvp('sudo', ['sudo', exe, *cmd])
def elevate():
system = platform.system()
if system == 'Linux':
linux_elevation()
elif system == 'Windows':
windows_elevation()
if __name__ == '__main__':
elevate()
print('The final command...')
i look forward to your examples. what i want to do is in a project that will have several processes and needs root, to limit the processes that have root powers to just those that need it (1 or 2). if i can figure out how to have my script get the file data when the tarfile module is extracting a tar archive, or how to have my script provide the data when it is creating a tar archive. the archive can be handled but i also need to handle all the data on the other end, too. this is getting to be a complex project.