1

How can i change to root user providing my password in the script?

I have this code

import os

# change to root user

# changing to root call this function
# example
os.sytem('reboot')

PS. not only this function but iptables too, so i need to change to root with out typing the password because i want to be automated.

Falcon Ryu
  • 475
  • 1
  • 6
  • 17
  • 1
    use `visudo`: try it before. [Link](https://askubuntu.com/a/168885/772449) – Benyamin Jafari Aug 24 '18 at 08:38
  • 3
    Possible duplicate of [How to execute os.\* methods as root?](https://stackoverflow.com/questions/1636136/how-to-execute-os-methods-as-root) – abc Aug 24 '18 at 08:41
  • You should also avoid storing login credential (username, password) in your code. If you're curious why take a look at [this](https://security.stackexchange.com/a/150601) – Jakob Sachs Aug 24 '18 at 08:43
  • Take a look at this thread: https://stackoverflow.com/questions/5191878/change-to-sudo-user-within-a-python-script Use some part of the program for root user as a sub-process.i.e Use subprocess import instead of using os. – Delegate Aug 24 '18 at 08:45

1 Answers1

0

If you don't want to do anything after the call to reboot, you can use os.exec*() to replace the current Python process with sudo, which will switch to the root user. Then, have sudo execute reboot as below.

import os
import shutil


SUDO_PATH = shutil.which('sudo')

if SUDO_PATH is None:
    raise OSError('cannot find sudo executable')

os.execl(SUDO_PATH, SUDO_PATH, 'reboot')

For the cases where you wish do something after executing an external process, use subprocess.run().

Peter Sutton
  • 1,145
  • 7
  • 20