2012-11-06 79 views
2

我有一段代碼,我想以非root用戶身份運行。如果程序以非root用戶身份運行,則不需要發生任何事情。但是,如果程序以root身份運行,則需要刪除root權限,執行代碼段,然後再次啓用root權限。你如何編寫啓用/禁用代碼?Python禁用並啓用Root權限

+0

這不能在安全,沒有分叉一個新的進程來完成。如果您以可以重新獲得root權限的方式刪除root權限,則沒有任何措施可以防止攻擊者在執行錯誤操作之前修改已執行的代碼。 – ThiefMaster

+0

你可以啓動'python'作爲'root'(sudo python) –

回答

0

嘗試以下操作:

import os 
print "user who executed the code: %d" % os.getuid() 
print "current effective user: %d" % os.geteuid() 
if os.getuid() == 0: 
    os.seteuid(65534) # user id of the user "nobody" 
    print "current effective user: %d" % os.geteuid() 
    # do what you need to do with non-root privileges here, e.g. write to a file 
    print >> open("/tmp/foobar.txt", "w"), "hello world" 
    os.seteuid(0) 
print "current effective user: %d" % os.geteuid() 

運行此爲根輸出:

 
user who executed the code: 0 
current effective user: 0 
current effective user: 65534 
current effective user: 0 
+0

如何獲取執行代碼的用戶的用戶標識? – user1802143

+0

@ user1802143 - 您可以檢查os.getuid()'的輸出。如果它等於零,那麼root執行代碼。我已經更新了這個例子來證明這一點。 – del

+0

我對稱爲sudo的用戶感興趣。當使用sudo時,uid爲0.有沒有辦法獲得sudo調用者的uid? – user1802143

0

嘗試os.getuid()os.setuid()。您可以使用它們在腳本中切換用戶。

+0

可能你需要使用['os.geteuid()'](http://docs.python.org/2/library/os.html代替#os.geteuid)和['os.seteuid()'](http://docs.python.org/2/library/os.html#os.seteuid)。否則,在刪除它們之後,無法再獲取root權限。 – del