Thursday, October 6, 2022

[SOLVED] How to create Python virtual environment with super user privileges

Issue

After creating Python virtual environment and activating it with:

sudo pip install virtualenv

virtualenv venv
source venv/bin/activate 

I can pip install locally inside of the virtual environment as well as to run other Pythons scripts still using a "local" or "virtual environment" that is defined inside of the ./venv folder. One of the Python scripts that I want to run requires a root user permissions (it tries to set os.setegid(1)). Trying to run it raises an error asking me to run it with admin privileges. But when I add sudo at front of the python my_script.py command the virtual environment breaks and doesn't load the modules installed locally (in virtual environment). Is there a way to run the python scripts in virtual environment and yet as super user (with sudo)?

Below is the Python snippet that if executed on Linux machine will raise the Operation not permitted error asking for root credentials:

import os
os.setegid(1)
OSError: [Errno 1] Operation not permitted

Solution

Your question is a little vague.

If you want to copy all your user modules into venv, try this

  • In user, without venv, do this in the venv folder pip freeze > requirements.txt
  • Activate venv and do this pip install -r requirements.txt This should install all your user modules into the venv

If you want to elevate your python script to sudo, try this

chmod 740 my_script.py

I am not a linux user, so I may be using the wrong chmod number, please use the appropriate one for elevating user privalage, but hope you get the gist For chmod, see here

Edit:

Try doing this in your python script

os.chmod(path, mode);

Mode Options:

stat.S_ISUID − Set user ID on execution.

stat.S_ISGID − Set group ID on execution.

stat.S_ENFMT − Record locking enforced.

stat.S_ISVTX − Save text image after execution.

stat.S_IREAD − Read by owner.

stat.S_IWRITE − Write by owner.

stat.S_IEXEC − Execute by owner.

stat.S_IRWXU − Read, write, and execute by owner.

stat.S_IRUSR − Read by owner.

stat.S_IWUSR − Write by owner.

stat.S_IXUSR − Execute by owner.

stat.S_IRWXG − Read, write, and execute by group.

stat.S_IRGRP − Read by group.

stat.S_IWGRP − Write by group.

stat.S_IXGRP − Execute by group.

stat.S_IRWXO − Read, write, and execute by others.

stat.S_IROTH − Read by others.

stat.S_IWOTH − Write by others.

stat.S_IXOTH − Execute by others.

Example Usage

os.chmod("path_to/my_script.py", S_IXUSR);


Answered By - Noob Science
Answer Checked By - Clifford M. (WPSolving Volunteer)