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.

4
  • 1
    use visudo: try it before. Link Commented Aug 24, 2018 at 8:38
  • 3
    Possible duplicate of How to execute os.* methods as root? Commented Aug 24, 2018 at 8:41
  • You should also avoid storing login credential (username, password) in your code. If you're curious why take a look at this Commented Aug 24, 2018 at 8:43
  • Take a look at this thread: stackoverflow.com/questions/5191878/… Use some part of the program for root user as a sub-process.i.e Use subprocess import instead of using os. Commented Aug 24, 2018 at 8:45

1 Answer 1

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().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.