Created
July 19, 2016 16:11
-
-
Save antevens/ec0ed88ce2f363c4dea4b71e74288879 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def run_as_root(func): | |
""" | |
A decorator to run a code block as the root user, assumes that user has | |
permissons to switch to root (see euid, ruid, suid) | |
""" | |
def inner(*args, **kwargs): | |
current_proc = multiprocessing.current_process() | |
logger.debug("Changing permissions for process: {0} with PID: {1}".format(current_proc.name, str(current_proc.pid))) | |
if sys.version > "2.7": | |
ruid, euid, suid = os.getresuid() | |
rgid, egid, sgid = os.getresgid() | |
logger.debug("UIDs before are: (ruid) {0}, (euid) {1}, (suid) {2}".format(ruid, euid, suid)) | |
logger.debug("GIDs before are: (rgid) {0}, (egid) {1}, (sgid) {2}".format(rgid, egid, sgid)) | |
logger.debug("Setting all UIDs/GIDs to 0") | |
# Make the actual permisson changes | |
os.setresuid(0, 0, 0) | |
os.setresgid(0, 0, 0) | |
try: | |
retval = func(*args, **kwargs) | |
finally: | |
# Restore original permissions | |
os.setresgid(rgid, egid, sgid) | |
os.setresuid(ruid, euid, suid) | |
else: | |
ruid = os.getuid() | |
euid = os.geteuid() | |
rgid = os.getgid() | |
egid = os.getegid() | |
logger.debug("UIDs before are: (ruid) {0}, (euid) {1}".format(ruid, euid)) | |
logger.debug("GIDs before are: (rgid) {0}, (egid) {1}".format(rgid, egid)) | |
logger.debug("Setting all UIDs/GIDs to 0") | |
# Make the actual permisson changes | |
os.setreuid(0, 0) | |
os.setregid(0, 0) | |
try: | |
logger.debug("Setting all UIDs/GIDs to 0") | |
retval = func(*args, **kwargs) | |
finally: | |
# Restore original permissions | |
os.setregid(rgid, egid) | |
os.setreuid(ruid, euid) | |
return retval | |
return inner |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment