2016-11-04 50 views
2

我有一個gui在林間空地製作,卡在一件事上。更改所有權和許可沒有終端 - Python

我有一個按鈕,可以更改所有權和權限;除了由root擁有的文件夾和文件之外,它工作正常。

有沒有辦法調用root privilages來運行此命令而不必在終端輸入root密碼?即或者在腳本中預定義它,或者激活密碼的彈出提示並提示它。下面的代碼的

實施例:

def on_button_clicked(self, widget): 
    path = {defined from combobox} 
    os.chdir(path) 

    uid = os.getuid() 
    gid = os.getgid() 

    for root, dirs, files in os.walk(path): 
     for d in dirs: 
      os.chown(os.path.join(root, d), uid, gid) 
      os.chmod(os.path.join(root, d), 0o755) 
     for f in files: 
      os.chown(os.path.join(root, f), uid, gid) 
      os.chmod(os.path.join(root, f), 0o755) 
+0

任何只以root身份運行腳本的理由對您不適用?你的「輸入終端沒有密碼」的要求對我來說有點不清楚。你的意思是你永遠不想輸入它*永遠*,或者你只是不希望腳本中斷提示輸入密碼? – skrrgwasme

+0

我想你可以使用[Envoy](https://github.com/kennethreitz/envoy) – Olian04

+0

原因,@skrrgwasme,是腳本在gui中工作正常,如果我使用os.system('sudo chown .....')命令使它看起來好像已經崩潰了,因爲實際上它正在等待用戶輸入的根passwrod。 –

回答

0

獎品進入@intepidhero爲proviving一些有用的鏈接;第一個做了詭計!

您只需確保您的用戶/組在sudoers中,並將folling代碼放在腳本的頭部,並且嘿presto ...您正在將您的應用程序升級到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 
+0

沒有必要把\ [解決]放在答案中。只需點擊投票箭頭下面的空白複選標記即可。這將[接受](http://stackoverflow.com/help/accepted-answer)答案作爲解決方案。 – skrrgwasme