Write to a file with sudo privileges in Python

user2824889 picture user2824889 · Sep 14, 2016 · Viewed 27.6k times · Source

The following code throws an error if it's run by a non-root user for a file owned by root, even when the non-root user has sudo privileges:

try:
  f = open(filename, "w+")
except IOError:
  sys.stderr.write('Error: Failed to open file %s' % (filename))
f.write(response + "\n" + new_line)
f.close()

Is there a way to run open(filename, "w+") with sudo privileges, or an alternative function that does this?

Answer

L3viathan picture L3viathan · Sep 14, 2016

You have a few options:

  • Run your script as root or with sudo
  • Set the setuid bit and have root own the script (although on many systems this won't work with scripts, and then the script will be callable by anyone)
  • Detect that you're not running as root (os.geteuid() != 0), then call yourself with sudo infront (which will ask the user to enter their password) and exit:

import os
import sys
import subprocess

if os.geteuid() == 0:
    print("We're root!")
else:
    print("We're not root.")
    subprocess.call(['sudo', 'python3', *sys.argv])
    sys.exit()

Calling it looks like this:

$ python3 be_root.py
We're not root.
Password:
We're root!