简体   繁体   中英

Change to root user in python

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM