你可以做的另一件事就是让你的脚本自动调用sudo,如果它没有以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时间戳,以便下次运行该脚本时,将再次需要该密码。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐