Search code examples
pythonbashsubprocesssudo

run bash script with elevated privileges from subprocess python multithreaded call


I'm programming in python on linux, and I am using multiprocessing_pool.apply_async to call a bash script using subprocess.check_output

The bash script is calling alien and rpmbuild. The alien command needs to run as root, and because of this the rpmbuild command does also, following a root sed command to correct some rpm idiosyncrasies.

At the moment, if I want to convert several debs to rpms, I have to enter my admin password, several times.

Is there a way that I can enter my admin password only once? ie that the script is always called with its different variables as new processes, but always elevated privileges following one password entry? At the moment I am using pkexec to call the script with sudo being used in the script itself.

Many thanks


Solution

  • If you run the python script as super-user, the script should not ask you a password:

    $ sudo python -c "import os ; os.system('whoami')"
    root
    

    So run your thing as usual but with sudo before python. If you need to run multiple python scripts and type your password only once, type sudo su. You will then be root for all commands (without prepending sudo) until you close the terminal session.

    Alternative ways to give the password:

    1. You can use sudo -A if you want a gui prompt to appear for the password.
    2. You can use sudo -S if you want to pass the password as stdin.

    Each process has its own user, you will have to create multiple processes to have multiple users.