1

I'm trying to run only a part of my script task.py in sudo mode. Ideally I would run task.py with the following structure:

if __name__ == '__main__':
    print('running normal parts')        
    .            .              .
    . [running normal commands] .
    .            .              .

    print('running sudo parts')
    .            .              .
    .  [running sudo commands]  .
    .            .              .

where I don't have to enter a password for the sudo parts of the script so that I can just make a single call $ python task.py from command line.

Is there a nice to tell Python to run the second block as sudo? I saw the subprocess module had a way to call a command with sudo privelages, but I'd rather not put the "sudo parts" into a separate script to do the "running sudo commands" part.

2
  • Possible dupes: this and this. Commented Aug 14, 2017 at 20:03
  • 1
    sudo won't run commands as root without having to type password, unless if you define a rule for that in /etc/sudoers to run a command as user or root without password. You need to be extra cautious with that. Commented Aug 14, 2017 at 20:24

1 Answer 1

1

I would highly recommend putting the sudo parts into a separate script just as the documentation recommended. That approach improves the security posture of your script dramatically as only the part necessary to execute with elevated privileges does (aka "least privilege"--a fundamental security principle).

I haven't read that documentation in detail, but I suspect it also mentions limiting write privileges to the sudo portion of the script as well and any file or resource that it may read from.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.