Skip to content

Instantly share code, notes, and snippets.

@ms8r
Created June 19, 2016 11:39
Show Gist options
  • Save ms8r/b9252b70ae2c938cc2bacf09fab02c15 to your computer and use it in GitHub Desktop.
Save ms8r/b9252b70ae2c938cc2bacf09fab02c15 to your computer and use it in GitHub Desktop.
Python: Use sudo to re-launch a script as root
# This is how I ensure a Python script is launched as root, and automatically
# call 'sudo' to re-launch it as root if not.
# I found it useful to check the parameters are valid *before* re-launching as
# root, so I don’t have to enter the sudo password if there is a problem with
# the parameters, or I just want the help message.
import os
import sys
# At this point we may be running as root or as another user
# - Check the parameters are valid - show an error if not
# - Show the help message if requested
# Don't do any work or anything time-consuming here as it will run twice
if os.geteuid() != 0:
# os.execvp() replaces the running process, rather than launching a child
# process, so there's no need to exit afterwards. The extra "sudo" in the
# second parameter is required because Python doesn't automatically set $0
# in the new process.
os.execvp("sudo", ["sudo"] + sys.argv)
# Now we are definitely running as root
# - Make the changes to the system settings (e.g. Apache config)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment