Modifying privileges with python

Asked

Viewed 44 times

2

I am facing the following problem, I am increasing the privileges with "Elevated", but after running the.mkdir (), I would like him to lose his privileges and return to being an ordinary 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, it looks true where it means that he is with super power.

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

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

thank you

1 answer

2


After doing the operation you need privileges, enter this code:

sudo_uid = int(os.getenv("SUDO_UID"))
sudo_gid = int(os.getenv("SUDO_GID"))

# drop root privileges
os.setresgid(sudo_gid, sudo_gid, -1)
os.setresuid(sudo_uid, sudo_uid, -1)

To raise the privileges again:

os.setresgid(0, 0, -1)
os.setresuid(0, 0, -1)
  • Don’t forget to import the pwd module

Browser other questions tagged

You are not signed in. Login or sign up in order to post.