当前位置: 首页 > 工具软件 > Git.php > 使用案例 >

php 自动部署git仓库

公良俊楚
2023-12-01

部署代码

<?php
//git webhook 自动部署脚本
//项目存放物理路径
$path = "/home/wwwroot/default/naifen";
$requestBody = file_get_contents("php://input");
if (empty($requestBody)) {
    die('send fail');
}
$content = json_decode($requestBody, true);
//若是主分支且提交数大于0
if ($content['ref']=='refs/heads/master' && $content['total_commits_count']>0) {
    $res = shell_exec("cd {$path}  && git reset --hard origin/master && git fetch --all && sudo git pull");
    $res_log = '-------------------------'.PHP_EOL;
    $res_log .= $content['user_name'] . ' 在' . date('Y-m-d H:i:s') . '向' . $content['repository']['name'] . '项目的' . $content['ref'] . '分支push了' . $content['total_commits_count'] . '个commit:' . PHP_EOL;
    $res_log .= $res.PHP_EOL;
    file_put_contents("git-webhook.txt", $res_log, FILE_APPEND);//追加写入
}
echo '很棒:'.date('y-m-d H:i:s');

不使用sudo git pull 拉去代码可能会因为权限问题失败(因为运行脚本的用户是www)

所以要使用sudo

但普通用户没有sudo权限,所以需要设置

linux给用户添加sudo权限: 
非root用户,linux下面运行sudo命令,会提示类似: 
xxxis not in the sudoers file.  This incident will be reported. 
这里,xxx是用户名称,然后导致无法执行sudo命令,这时候,如下解决:

进入超级用户模式。也就是输入"su -",系统会让你输入超级用户密码,输入密码后就进入了超级用户模式。(当然,你也可以直接用root用)

添加文件的写权限。也就是输入命令"chmod u+w /etc/sudoers"。 

编辑/etc/sudoers文件。也就是输入命令"vim /etc/sudoers",进入编辑模式,找到这一 行:"root ALL=(ALL) ALL"在起下面添加"xxx ALL=(ALL) ALL"(这里的xxx是你的用户名),然后保存退出。

撤销文件的写权限。也就是输入命令"chmod u-w /etc/sudoers"。 
然后就行了。

 类似资料: