如何在 git post-receive hook 中以 root 身份执行命令

djh*_*eru 13 linux sudo bash git upstart

我最近刚刚在服务器上为作为 Upstart 服务运行的 Web 应用程序设置了一个远程 git repo。我想使用 post-receive 挂钩来触发更新应用程序代码所需的操作,然后停止然后重新启动 upstart 服务。这是我的 repo.git/hooks/post-receive 文件:

#!/bin/bash
export GIT_WORK_TREE=/var/www/current/myapp/
echo "Checking out new files and restarting app"
echo $USER
git checkout -f
sudo /sbin/stop myapp-service
sudo /sbin/start myapp-service
Run Code Online (Sandbox Code Playgroud)

根据我在这里读到的信息:askUbuntu.com,让 upstart 命令以 root 身份执行的方法是编辑我的 visudo 文件。这是相关的片段:

%sudo   ALL=(ALL:ALL) ALL
admin   ALL=(ALL:ALL) NOPASSWD: /sbin/start myapp-service /sbin/stop myapp-service
Run Code Online (Sandbox Code Playgroud)

但是当我 git push 到遥控器时,我得到如下输出:

$ git commit -am "test" && git push prod master
[master 59ffccd] test
 1 file changed, 1 insertion(+), 1 deletion(-)
Counting objects: 11, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (6/6), 544 bytes, done.
Total 6 (delta 4), reused 0 (delta 0)
remote: Checking out new files on production and restarting app
remote: admin
remote: 
remote: sudo: no tty present and no askpass program specified
remote: Sorry, try again.
Run Code Online (Sandbox Code Playgroud)

我已经检查过正确的用户正在执行接收后脚本(管理员,如上所回)。

有人可以帮助我停止然后在 git post-receive 挂钩脚本中启动 Upstart 作业吗?如果 Python、PHP 或 node.js javascript 脚本能够比 bash 更容易地执行 upstart 命令,那么它们也可以接受(我是 bash 新手)

我查看了我的身份验证日志,这就是我所拥有的:

Apr 24 19:35:21 myhost01 sudo: pam_unix(sudo:auth): auth could not identify password for [admin]
Apr 24 19:35:21 myhost01 sudo: pam_unix(sudo:auth): conversation failed
Apr 24 19:35:21 myhost01 sudo: pam_unix(sudo:auth): auth could not identify password for [admin]
Apr 24 19:35:21 myhost01 sudo: pam_unix(sudo:auth): conversation failed
Apr 24 19:35:21 myhost01 sudo: pam_unix(sudo:auth): auth could not identify password for [admin]
Apr 24 19:35:21 myhost01 sudo:    admin : 3 incorrect password attempts ; TTY=unknown ; PWD=/home/admin/myapp.git ; USER=root ; COMMAND=/s$
Apr 24 19:35:21 myhost01 sudo: unable to execute /usr/sbin/sendmail: No such file or directory
Apr 24 19:35:21  myhost01 sudo: pam_unix(sudo:auth): conversation failed
Run Code Online (Sandbox Code Playgroud)

use*_*067 8

您需要使用逗号分隔 sudoers 文件中的命令。现在,您正在授权一个命令:/sbin/start myapp-service /sbin/stop myapp-service.

你需要写admin ALL=(ALL:ALL) NOPASSWD: /sbin/start myapp-service, /sbin/stop myapp-service.


djh*_*eru 7

好的,我想通了。我必须创建一个单独的脚本,其中只包含我想以 root 身份运行的命令。

#!/bin/bash
sudo /sbin/stop myapp-service
sudo /sbin/start myapp-service
Run Code Online (Sandbox Code Playgroud)

然后,在我的接收后脚本中:

#!/bin/bash
export GIT_WORK_TREE=/var/www/current/myapp/
set -x
echo "Checking out new files on production and restarting app"
echo $USER
git checkout -f
sudo /home/admin/restart-myapp
Run Code Online (Sandbox Code Playgroud)

最后在我的视觉中:

%sudo   ALL=(ALL:ALL) ALL
admin   ALL=(ALL) NOPASSWD: /home/admin/restart-myapp
Run Code Online (Sandbox Code Playgroud)

希望这对其他人有帮助