Skip to content Skip to sidebar Skip to footer

Python - Running Select Sections Of Code As Sudo

Is it possible to have a script that can be run without root access, but if root access is required, a password can be collected, and select pieces of the code can be run as sudo?

Solution 1:

here is another way to almost get what you want

import inspect
import os
def sudo_call(fn,*args):
    with open("some_test.py","wb") as f:
        f.write(inspect.getsource(fn))
        f.write("%s(*%r)"%(fn.__name__,args)
    os.system("echo <SUDO_PASSWORD> | sudo -S -p '' python some_test.py ")

def hello(a,b):
    print a+b

sudo_call(hello,[1,2])

Post a Comment for "Python - Running Select Sections Of Code As Sudo"