2

I wanted to write in a file which required root privilege.

  1. Run python script as Normal User
  2. Switch to root privilege using password( password can be provided in code)
  3. Edit file which needed root privilege
  4. Back to normal user
  • This isn't a question. – Nick Bailey Apr 23 '22 at 05:37
  • 1
    I don't think this is really possible. Only a privileged process can change its userid. So it has to start as the root user. It can then switch to the normal user, and can later switch back to root. – Barmar Apr 23 '22 at 05:37
  • 1
    The Python script can use `subprocess` to execute `sudo` to run another script as root. – Barmar Apr 23 '22 at 05:38
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Apr 23 '22 at 08:08

1 Answers1

0

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

Lima
  • 257
  • 1
  • 8