Sudo 不會以其他使用者身分執行指令

Sudo 不會以其他使用者身分執行指令

我試圖讓獨角獸伺服器在伺服器啟動時啟動。我建立了一個 shell 腳本,如果我以 ubuntu 使用者身分登入並運行,該腳本就可以工作

/etc/init.d/unicorn start

外殼腳本

#!/bin/sh

case "$1" in
start)
    cd /home/ubuntu/projects/asbest/current/
    unicorn_rails -c /home/ubuntu/projects/asbest/current/config/unicorn.rb -D -E production

;;
stop)
    if ps aux | awk '{print $2 }' | grep `cat ~/projects/asbest/current/tmp/pids/unicorn.pid`> /dev/null; then kill `cat ~/projects/asbest/current/tmp/pids/uni$
;;
restart)
    $0 stop
    $0 start
;;
esac

當我重新啟動伺服器時,我注意到獨角獸伺服器沒有監聽套接字。由於我以 ubuntu 使用者身份成功運行了程式碼,因此我修改了腳本以使其始終透過 sudo 使用 ubuntu 使用者。

#!/bin/sh

case "$1" in
start)
    cd /home/ubuntu/projects/asbest/current/
    sudo -u ubuntu unicorn_rails -c /home/ubuntu/projects/asbest/current/config/unicorn.rb -D -E production
;;
stop)
    if ps aux | awk '{print $2 }' | grep `cat ~/projects/asbest/current/tmp/pids/unicorn.pid`> /dev/null; then sudo -u ubuntu kill `cat ~/projects/asbest/current/tmp/pids/uni$
;;
restart)
    $0 stop
    $0 start
;;
esac

重新啟動後獨角獸仍然無法啟動,所以我嘗試從命令列運行腳本。現在我收到以下錯誤

sudo: unicorn_rails: command not found

我已經仔細搜尋過可能導致此問題的原因,但恐怕我對 Linux 的了解有限。據我所知,雖然 sudo 應該使用 ubuntu 使用者來執行命令,但它仍然使用 root 使用者的環境,而 root 使用者沒有配置為運行 ruby​​ 或 unicorn。有人有這方面的經驗嗎?

答案1

UNICORN_*像這樣使用全域變數:

UNICORN_HOME=/the/path
UNICORN_RAIL=${UNICORN_HOME}/unicorn_rail
UNICORN_CONFIG=${UNICORN_HOME}/config/unicorn.rb
UNICORN_PID=${UNICORN_HOME}/tmp/pids/unicorn.pid
UNICORN_USER=ubuntu

sudo -u ${UNICORN_USER} ${UNICORN_RAIL} -c $UNICORN_CONFIG -D -E production

另一個好方法是提取全域變數/etc/default/unicorn

UNICORN_HOME=/the/path
UNICORN_RAIL=${UNICORN_HOME}/unicorn_rail
UNICORN_CONFIG=${UNICORN_HOME}/config/unicorn.rb
UNICORN_PID=${UNICORN_HOME}/tmp/pids/unicorn.pid
UNICORN_USER=ubuntu

並在您的初始化腳本中新增更改所有變數:

if [ -f /etc/default/unicorn ]; then
    . /etc/default/unicorn
fi

答案2

不要使用sudo,而是嘗試使用su [username],然後執行該命令。

答案3

您需要指定以下路徑unicorn_rails

UNICORN_HOME=/home/ubuntu/projects/asbest/current
cd $UNICORN_HOME
sudo -u ubuntu $UNICORN_HOME/unicorn_rails -c $UNICORN_HOME/config/unicorn.rb -D -E production

您是否正確配置了 sudo?

相關內容