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

时间:2023-01-24 14:15:15

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

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

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

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

2 个解决方案

#1


26  

The other thing you can do is have your script automatically invoke sudo if it wasn't executed as root:

您可以做的另一件事是让脚本在没有以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

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.

使用sudo -k进行测试,清除sudo时间戳,以便下次运行脚本时再次需要密码。

#2


5  

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

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

#1


26  

The other thing you can do is have your script automatically invoke sudo if it wasn't executed as root:

您可以做的另一件事是让脚本在没有以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

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.

使用sudo -k进行测试,清除sudo时间戳,以便下次运行脚本时再次需要密码。

#2


5  

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

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