一、在服务器网站根目录添加个 gitHook.php
/**
*gitHook.php
* Created by: Lqz.
* Description:
* User: Administrator
* CreateTime: 2018/7/27 0027 12:56
*/
//git webhook 自动部署脚本
//项目存放物理路径
if ($_SERVER['HTTP_HOST'] == 'www.xxx.com') {
$path = "/usr/local/nginx/html/xxx_online";
$ref = 'refs/heads/master';
} elseif ($_SERVER['HTTP_HOST'] == 'dev.xxx.com') {
$path = "/usr/local/nginx/html/xxx_dev";
$ref = 'refs/heads/dev';
} else {
echo "host is error!!";
exit;
}
$requestBody = file_get_contents("php://input");
print_r($requestBody);
if (empty($requestBody)) {
die('send fail');
}
$content = json_decode($requestBody, true);
#file_put_contents("Uploads/git-content.txt", $res_log);//查看传递过来的参数 , 每个git平台应该都是完全一样的
//若是主分支且提交数大于0
if ($content['ref'] == $ref && count($content['commits']) > 0) {
$res = shell_exec("cd {$path} && sudo git fetch --all 2>&1");//以nginx用户运行
// $res = shell_exec("cd {$path} && sudo git reset --hard origin/develop ");
$res .= shell_exec("cd {$path} && sudo git pull origin dev 2>&1");
// $res .= shell_exec("cd {$path} && sudo git stash pop 2>&1");
// $res .= shell_exec("cd {$path} && sudo chown -R apache:apache *");
$res_log = '-------------------------' . PHP_EOL;
$res_log .= $content['pusher']['name'] . ' 在' . date('Y-m-d H:i:s') . '向' . $content['repository']['name'] . '项目的' . $content['ref'] . '分支push了' . count($content['commits']) . '个commit:' . PHP_EOL;
$res_log .= $res . PHP_EOL;
file_put_contents("Uploads/git-webhook.txt", $res_log, FILE_APPEND);//追加写入
}
在这:如果执行可能会报git错误
sudo: sorry, you must have a tty to run sudo
或
sudo: no tty present and no askpass program specified
二、给web端 运行账号 sudo 权限,修改/etc/sudoers(一般是 nobody, Linux默认的web访问账号,也有www的等, 具体看代码执行的账号是什么,代码也要给 nobody可执行的权限,否者 git pull不下来)
修改内容如下(我用的是nobody):
1. 编辑 /etc/sudoers
1)Defaults requiretty,修改为 #Defaults requiretty,表示不需要控制终端。
2)Defaults requiretty,修改为 Defaults:nobody !requiretty,表示仅 nobody 用户不需要控制终端。
如果修改为 Defaults:%nobody !requiretty,表示仅 nobody 组不需要控制终端。
其实只要注释掉)Defaults requiretty 那个就可以了。表示在执行的时候不打开终端。
2.添加一行
nobody ALL=(ALL) NOPASSWD:ALL #这个地方就是你的web执行账号
三、git免密执行命令:保存服务器 root 执行git pull是输入的账号密码就可以了(两种方法)
一种是 在网站根目录 .git/config
[root@47.105.52.109 dsrwtest]$ cat .git/config
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
[remote "origin"]
url = http://你的账号:你的git密码@git.coding.net/xxx/dsrw.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "develop"]
remote = origin
merge = refs/heads/develop
[user]
email = xxx@xxx.com
name = xx
第二种:
git config --global credential.helper store
再执行git pull 再次输入账号密码,git会自动记住
第四部 git 代码仓库配置webhook,网站访问的githook.php填写入git代码仓库的网站的 webhook配置位置, 这样就可以了:
www.xxxx.com/gitHook.php