Sudo不会以另一个用户的身份执行命令

我试图让服务器启动时启动一个独angular兽服务器。 我创build了一个shell脚本,如果我以ubuntu用户身份login并运行,就可以运行

/etc/init.d/unicorn start 

Shell脚本

 #!/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 

当我重新启动服务器时,我注意到独angular兽服务器没有监听套接字。 由于我作为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 

重新启动独angular兽后,仍然不会启动,所以我试图从命令行运行脚本。 现在我得到以下错误

 sudo: unicorn_rails: command not found 

我已经search了什么可能导致这个,但我恐怕我已经挖掘了我对Linux有限的理解。 从我所能理解的是,尽pipesudo应该使用ubuntu用户来执行这些命令,但它仍然使用root用户的环境,这个root用户没有configuration成运行ruby或者独angular兽。 有没有人有这方面的经验?

使用全球variablesUNICORN_*像这样:

 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提取全局variables:

 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 

并在你的初始化脚本中添加更改所有的variables:

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

不要使用sudo ,请尝试使用su [username] ,然后执行命令。

您需要指定unicorn_rails的path:

 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 

你有没有适当的configurationsudo?