Sudoは別のユーザーとしてコマンドを実行しません

Sudoは別のユーザーとしてコマンドを実行しません

私はサーバの起動時にユニコーンサーバを起動させようとしています。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

サーバーを再起動すると、Unicorn サーバーがソケットをリッスンしていないことに気付きました。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 ユーザーを使用する必要があるにもかかわらず、ruby や unicorn を実行するように設定されていない root ユーザーの環境を使用しているということです。これについて経験のある方はいますか?

答え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

そして、init スクリプトですべての変数を次のように変更します:

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 を適切に設定しましたか?

関連情報