running a command as a super user from a python script

后端 未结 8 1222
别跟我提以往
别跟我提以往 2020-11-28 06:15

So I\'m trying to get a process to be run as a super user from within a python script using subprocess. In the ipython shell something like

proc = subproces         


        
8条回答
  •  悲&欢浪女
    2020-11-28 07:17

    I tried all the solutions, but did not work. Wanted to run long running tasks with Celery but for these I needed to run sudo chown command with subprocess.call().

    This is what worked for me:

    To add safe environment variables, in command line, type:

    export MY_SUDO_PASS="user_password_here"
    

    To test if it's working type:

    echo $MY_SUDO_PASS
     > user_password_here
    

    To run it at system startup add it to the end of this file:

    nano ~/.bashrc  
    

    #.bashrc
    ...
    existing_content:
    
      elif [ -f /etc/bash_completion ]; then
        . /etc/bash_completion
      fi
    fi
    ...
    
    export MY_SUDO_PASS="user_password_here"
    

    You can add all your environment variables passwords, usernames, host, etc here later.

    If your variables are ready you can run:

    To update:

    echo $MY_SUDO_PASS | sudo -S apt-get update
    

    Or to install Midnight Commander

    echo $MY_SUDO_PASS | sudo -S apt-get install mc
    

    To start Midnight Commander with sudo

    echo $MY_SUDO_PASS | sudo -S mc
    

    Or from python shell (or Django/Celery), to change directory ownership recursively:

    python
    >> import subprocess
    >> subprocess.call('echo $MY_SUDO_PASS | sudo -S chown -R username_here /home/username_here/folder_to_change_ownership_recursivley', shell=True)
    

    Hope it helps.

提交回复
热议问题