Search code examples
pythonsecuritysubprocesssudo

run part of python script as sudo


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.


Solution

  • 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.