I wanted to write in a file which required root privilege.
- Run python script as Normal User
- Switch to root privilege using password( password can be provided in code)
- Edit file which needed root privilege
- Back to normal user
I wanted to write in a file which required root privilege.
This question was answered here.
You can prompt the user for sudo access:
import os, subprocess
def prompt_sudo():
ret = 0
if os.geteuid() != 0:
msg = "[sudo] password for %u:"
ret = subprocess.check_call("sudo -v -p '%s'" % msg, shell=True)
return ret
if prompt_sudo() != 0:
# the user wasn't authenticated as a sudoer, exit?
The sudo -v switch update the user's cached credentials (see man sudo).
EDIT: This code works only if you run the script from the terminal