2013-03-02 19 views
3

我正在編寫一個程序,它在第一次運行時執行配置更改(在/etc中創建文件)時臨時需要root。如何以編程方式使用sudo?即將sudo集成到我的GUI中

如何通過在圖形對話框中詢問用戶密碼來暫時獲得root?

該程序使用Qt,如果它只適用於Ubuntu,我相當高興,但我不想假設他們有gksudo或任何安裝。我也不能使用SUID

我能想到的唯一的事情就是提供我自己的密碼對話框,並通過system()(或其不太安全的表兄弟之一)將它提供給命令行sudo二進制文件。

雖然這看起來很詭異 - 命令行前端通常是一個可怕的想法,應該不惜一切代價避免。那麼有沒有更好的方法?也許有libsudo,或使用IPC的某種方法?

注:This is not a duplicate.或者至少,那裏的答案不把它當作我問的問題。

回答

0

man sudo

-A   Normally, if sudo requires a password, it will read it from the 
       user's terminal. If the -A (askpass) option is specified, a 
       (possibly graphical) helper program is executed to read the user's 
       password and output the password to the standard output. If the 
       SUDO_ASKPASS environment variable is set, it specifies the path to 
       the helper program. Otherwise, if /etc/sudo.conf contains a line 
       specifying the askpass program, that value will be used. For 
       example: 

        # Path to askpass helper program 
        Path askpass /usr/X11R6/bin/ssh-askpass 

       If no askpass program is available, sudo will exit with an error. 

無論您使用的是安裝在許多系統上的ssh-askpass或者你寫你自己的密碼提示命令你,然後提供給須藤。這仍然有點兒麻煩,但是您不必擔心將密碼傳遞給sudo。

+0

是的,我想這是一個合理的解決方案。儘管如此,這還意味着我不能將我的程序作爲單個二進制文件分發。 – Timmmm 2013-03-02 00:38:31

+1

嗯,從技術上說,你可以自己做askpass可執行文件,並檢查sudo是否是調用者,然後改變程序的行爲,使其充當askpass程序。或者,你可以使用某種打包二進制。 – nemo 2013-03-02 02:23:07

+1

sudo -A可能存在問題:它可能會清除sudo超時,從而導致在腳本中爲每個sudo調用啓動SUDO_ASKPASS程序。請參閱[以圖形方式在bash腳本中詢問密碼並保留默認的sudo超時設置。](http://unix.stackexchange.com/q/81181/1321) – jfs 2014-09-18 04:55:29