1

I am facing the following problem, I am raising the provilegios with "Elevate" but after running os.mkdir () I would like him to lose his privileges and return to being a common user.

import os
import sys
import subprocess
from elevate import elevate
from os import popen

def is_root():
  return os.getuid() == 0

print("before ", is_root())
user = os.getlogin()

elevate(graphical=False)
username = input("Enter the name of the user to be created in /home: ")
os.mkdir('/home/' + username)
print(os.listdir('/home'))
print("after ", is_root())

I made a checker if the user is privileged and even after running it appears as true where it means that he is with super power.

[garden@server ~]$ python3 mkdir.py
before  False
[sudo] password for garden:
before  True
Enter your name : user10
['garden', 'user10']
after  True

I would like to know if there is a way to elevate privileges and then withdraw, so that in case of an exception the code is not running with an elevated user.

thank you

TheGarden
  • 43
  • 4
  • I believed elevate is for the script itself rather than the user of your python code. What kind of privileges are you trying to allow that requires 'sudo' ? One option would be to exit the program once the privelege has been 'used' and relaunch as a standard user. Also have a look at this for Windows. If you need the code to work on both UNIX/Windows then you probably have to do some further reading. https://stackoverflow.com/questions/130763/request-uac-elevation-from-within-a-python-script – Jason Chia May 25 '20 at 13:34
  • 1
    `elevate` uses `sudo` (or an equivalent) under the hood, so I would just be explicit and use `subprocess` to run `sudo mkdir ...` in the first place. It won't be significantly more expensive, because `elevate` is restarting your process anyway. – chepner May 25 '20 at 13:38

0 Answers0