在Python脚本中以root身份进行身份验证

16 投票
2 回答
17700 浏览
提问于 2025-04-16 13:10

我正在Linux系统层面上用Python做一个项目。 所以我想知道,如果我以普通用户的身份运行我的代码,而我又需要访问系统文件,这样的话就需要有管理员权限。 那么,我该如何提示输入管理员密码,并以超级用户的身份继续运行代码呢? 我想了解一下,如何在提示输入密码的情况下,以超级用户身份运行Python脚本。

任何帮助都将不胜感激。 提前谢谢你们。

2 个回答

6
import os
euid = os.geteuid() 
if euid != 0:
  raise EnvironmentError, "need to be root"
  exit()

这段话的意思是,程序在运行的时候不会中途弹出提示,而是会要求用户重新以超级用户(sudo)或者管理员(root)的身份来运行这个程序。

31

你还可以让你的脚本在没有以管理员身份运行时自动调用sudo:

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时间戳,下次运行脚本时就会再次要求输入密码。

撰写回答