我正在用Python在Linux系统级别上进行项目开发。因此,如果我以普通用户身份运行代码并访问系统文件,则需要根权限,那么我该如何提示输入根密码,并以超级用户身份继续运行代码呢?
我想知道如何在提示输入密码后以超级用户身份运行Python脚本。
任何帮助将不胜感激。 提前感谢您的帮助。
另外一个做法是让你的脚本自动以超级用户身份运行,如果它没有作为root执行:
import os
import sys
euid = os.geteuid()
if euid != 0:
print "Script not started as root. Running sudo.."
args = ['sudo', sys.executable] + sys.argv + [os.environ]
# the next line replaces the currently-running process with the sudo
os.execlpe('sudo', *args)
print 'Running. Your euid is', euid
输出:
Script not started as root. Running sudo..
[sudo] password for bob:
Running. Your euid is 0
使用sudo -k
进行测试,以清除sudo的时间戳,这样下次运行脚本时就需要再次输入密码。
import os
euid = os.geteuid()
if euid != 0:
raise EnvironmentError, "need to be root"
exit()
这不会在脚本运行过程中提示用户,而是强制用户使用sudo或root重新运行它。