Skip to content

Instantly share code, notes, and snippets.

@skaslev
Forked from barneygale/sudo.py
Created April 15, 2016 09:00
Show Gist options
  • Save skaslev/cb82b3762f657144b4cedb64938d7357 to your computer and use it in GitHub Desktop.
Save skaslev/cb82b3762f657144b4cedb64938d7357 to your computer and use it in GitHub Desktop.
import sys, marshal, functools, subprocess
child_script = """
import marshal, sys, types;
fn, args, kwargs = marshal.load(sys.stdin)
marshal.dump(
types.FunctionType(fn, globals())(*args, **kwargs),
sys.stdout)
"""
def sudo(fn):
@functools.wraps(fn)
def inner(*args, **kwargs):
proc_args = [
"sudo",
sys.executable,
"-c",
child_script]
proc = subprocess.Popen(
proc_args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
send_data = marshal.dumps((
fn.func_code,
args,
kwargs))
recv_data = proc.communicate(send_data)[0]
return marshal.loads(recv_data)
return inner
@sudo
def whoami():
import os
return "I am: %d" % os.getuid()
if __name__ == '__main__':
print whoami()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment