python 脚本中的身份验证以 root 身份运行

发布于 2024-10-21 05:27:33 字数 185 浏览 5 评论 0原文

我正在 Linux 上用 Python 做一个系统级的项目。 所以,我想知道我是否以普通用户身份运行我的代码并且 如果我正在访问系统文件,那么它应该具有 root 权限, 那么我如何提示输入 root 密码并以超级用户身份运行进一步的代码。 我想知道如何以超级用户身份运行 python 脚本并提示密码。

任何帮助将不胜感激。 先感谢您..

I am doing a project in Linux at system level in Python.
So that, I want to know that if i am running my code as a normal user and
if i am accessing system files then it should have root permissions for it,
then how can i prompt for root password and run further code as superuser.
I want to know that, how to run python script as superuser with password prompt for it..

Any help will be appreciated.
Thank you in advance..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冰葑 2024-10-28 05:27:34

您可以做的另一件事是,如果脚本未以 root 身份执行,则让脚本自动调用 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 时间戳,以便下次脚本运行时运行它将再次要求密码。

The other thing you can do is have your script automatically invoke sudo if it wasn't executed as 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

Output:

Script not started as root. Running sudo..
[sudo] password for bob:
Running. Your euid is 0

Use sudo -k for testing, to clear your sudo timestamp so the next time the script is run it will require the password again.

看海 2024-10-28 05:27:34
import os
euid = os.geteuid() 
if euid != 0:
  raise EnvironmentError, "need to be root"
  exit()

这不会在脚本中间提示,而是强制用户使用 sudo 或以 root 身份重新运行它

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

This won't prompt in the middle of script but would rather force the user to re-run it with sudo or as root

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文