authentication in python script to run as root

China☆狼群 提交于 2019-11-27 14:02:03

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.

loosecannon
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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!