简体   繁体   English

在python中更改为root用户

[英]Change to root user in python

How can i change to root user providing my password in the script? 如何更改为root用户,在脚本中提供密码?

I have this code 我有这个代码

import os

# change to root user

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

PS. 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. 不仅是此功能,而且还有iptables,因此我需要更改为root而不输入密码,因为我想实现自动化。

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. 如果您在reboot电话后不想执行任何操作,则可以使用os.exec*()将当前的Python进程替换为sudo ,它将切换到root用户。 Then, have sudo execute reboot as below. 然后,让sudo执行如下reboot

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() . 对于您希望在执行外部过程后执行某些操作的情况,请使用subprocess.run()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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