TMSeth
TMSeth

Reputation: 21

How to run python code with root permissions in sourced environment

I have created pyenv environment (/home/username/python_env/) with some additional libraries (like PyYaml, Pillow etc). Everything is working fine until I need to change /etc/resolv.conf from inside of my tool. Additional part of code which I need to run is os.chroot and I can't do it without root permissions.

All operations are made for current user (which can change) so if I use sudo to execute my tool like sudo python src/tool-name/main.py then everything will be executed for root user instead for username.

Using sudo will affects:

Is there a way to request sudo just for small part of code and after that return to user permissions while my script is running?

Upvotes: 2

Views: 1118

Answers (1)

Sayeed
Sayeed

Reputation: 21

Running Python code with root permissions inside a virtual environment can be tricky, as you need to maintain the environment variables of the virtual environment while executing the code with elevated privileges. Here's a possible approach to achieve this:

  1. Activate the virtual environment in your user context.
  2. Use sudo -E to run the Python code with elevated privileges while preserving the environment variables.

Step 1: Activate the virtual environment (as a regular user):

$ source /home/username/python_env/bin/activate

Step 2: Run your Python code with sudo -E:

$ sudo -E python /path/to/your/code.py

The -E option tells sudo to preserve the user's environment, including the virtual environment variables set during activation.

With this approach, your Python code should be executed with root permissions while still using the virtual environment's Python interpreter and libraries.

Upvotes: 0

Related Questions