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?
You have a few options:
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!