root 是否可以以非 root 身分執行指令?

root 是否可以以非 root 身分執行指令?

我是 root 用戶,假設我想以另一個用戶身份運行任何應用程式。這可以在不切換到其他用戶的情況下實現嗎?

就像是

# google-chrome user=abc

我實際上是以非 root 使用者身分執行 CLI 程式。我已經設定了黏滯位元並且正在使用 setuid,因此程式以 root 權限運行。現在我system()在程式中使用來呼叫 GUI 應用程式。但我不想以 root 身分運行它,因此我只想暫時刪除該呼叫的 root 權限。

答案1

便攜式解決方案是:

su abc -c google-chrome

然而,由於 google-chrome 需要 X11 存取權限,除非您取消安全保護,否則這可能會失敗,這將是一個非常糟糕的主意,尤其是在以 root 身份運行時。

如果允許 X11 隧道/轉發,更好的方法是

ssh -X abc@localhost google-chrome

或者

ssh -Y abc@localhost google-chrome

答案2

簡短的回答:「是的,這是可能的」。

如果您想執行非 X 應用程序,則只需使用以下命令:

須藤 -u abc命令

如果您想以其他用戶身份運行某些 X 應用程序,但首先使用自己的桌面,則需要創建一個幫助程序腳本,這將使您的生活更簡單

  • 在你的主目錄下建立一個 bin 資料夾:

mkdir -p ~/bin

並使用您最喜歡的文字編輯器建立一個文件,~/bin/xsudo如下所示:

#!/bin/bash
# (C) serge 2012
# The script is licensed to all users of StackExchange family free of charge
# Fixes/Enhancements to the script are greatly appreciated. 
# 
# SUDO_ASKPASS has to be set to the path of ssh-askpass
# fix the following two lines if your distribution does not match this autodetection
. /etc/profile.d/gnome-ssh-askpass.sh
export SUDO_ASKPASS="${SSH_ASKPASS}"

SUDOUSERNAME="$1"
shift
xauth nlist "${DISPLAY}"|sudo -HA -u $SUDOUSERNAME env --unset=XAUTHORITY \
bash -c "xauth nmerge - ; $*"

然後使其可執行:

chmod +x ~/bin/xsudo

並以相同的方式使用它,sudo但沒有任何開關:

須藤用戶申請

享受。

PS強烈建議不要xsession從帳戶啟動!root

答案3

有一種方法可以在以 root 使用者登入時執行 chromium。如果你正常打開它,它會給你一個類似「chromium無法以root身份運行」的錯誤。

要運行它而不出現錯誤,right click請在桌面上使用以下命令建立一個新的啟動器:chromium-browser --user-data-dir。你可以隨意命名,保存,當你打開它時,它會給你 Chromium 瀏覽器。 (適用於 Ubuntu 10.04.4 LTS)

答案4

#! /bin/bash
#  (GPL3+) Alberto Salvia Novella (es20490446e)


execute () {
    function="${1}"
    command="${2}"
    error=$(eval "${command}" 2>&1 >"/dev/null")

    if [ ${?} -ne 0 ]; then
        echo "${function}: $error"
        exit 1
    fi
}


executeAsNonAdmin () {
    function="${1}"
    command="${2}"

    eval setPasswordAsker="SUDO_ASKPASS=/usr/libexec/openssh/ssh-askpass"
    run="runuser ${SUDO_USER} --session-command=\"${setPasswordAsker}\" --command=\"${command}\""
    execute "${function}" "${run}"
}


executeAsNonAdmin "" "${@}"

相關內容