Skip to content

Instantly share code, notes, and snippets.

@matteomattei
Created July 8, 2014 08:14
Show Gist options
  • Save matteomattei/737c8f9797e0c2f5eb36 to your computer and use it in GitHub Desktop.
Save matteomattei/737c8f9797e0c2f5eb36 to your computer and use it in GitHub Desktop.
How to execute commands with specific user privilege in Python under Linux
#!/usr/bin/env python
import sys,pwd,os
pw = pwd.getpwnam(sys.argv[1])
os.initgroups(sys.argv[1],pw.pw_gid)
env={"TERM":"xterm","USER":pw.pw_name,"HOME":pw.pw_dir,"SHELL":pw.pw_shell,"LOGNAME":pw.pw_name,"PATH":"/usr/bin:/bin:/opt/bin"};
os.setgid(pw.pw_gid);
os.setuid(pw.pw_uid);
os.execve(sys.argv[2],[],env);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment