ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

git自动更新功能

2026/8/7 19:03:33 拓冰建站 浏览量
git自动更新功能

确认权限

因为一般Linux系统网页用的wwwwww-data用户和用户组,所以要实现自动来去,首先要在www用户权限下生成ssh密钥,不然没有权限,其次就是,要把用root用户拉去的代码,批量改成www用户
在这里插入图片描述

1. 给www权限


vi  /etc/sudoers
www     ALL=(ALL)     NOPASSWD:/bin/chown,/bin/chmod,/usr/bin/git

2.切换www账户

一切操作在www用户下完成

给www账户添加git 邮箱和和用户名

sudo git config --global user.email "xxx@qq.com"
sudo git config --global user.name "finejade"

添加origin

如果remote- roigin 远程地址是http的,改成ssh的,可以使用ssh秘钥免登录提交

git remote -v
git remote remove origin
git remtoe add origin git@git.code.tencent.com:finejade/thinkphp6.git

生成密钥

生成密钥,一直下一步

 ssh-keygen -t rsa -C "332410549@qq.com"

在这里插入图片描述

把公钥填写到git个人账号的SSH密钥

在这里插入图片描述

编写自动拉去代码

  public function autopull(){$json = file_get_contents("php://input");file_put_contents('./a.txt',$json);//获取请求参数if (empty($json)) {die('request is empty');}$data = json_decode($json, true);$savePath =  Env::get('root_path');//密码if (isset($data['password'])) {$password = 'AJ8ENFEOWLS';//验证密码是否正确if ($data['password'] != $password) {header("HTTP/1.1 403 Forbidden");die('非法提交');}}//一定要在php.ini 配置文件中解除所有禁用 disable_funtions  exec 方法// git放弃修改,强制覆盖本地代码echo shell_exec("cd {$savePath} && git checkout ."); // git checkout// echo shell_exec("cd {$savePath} && git pull {$gitPath}  2>&1");$res = PHP_EOL . "pull start " . PHP_EOL;$res .= shell_exec("cd " . $savePath . " && git pull origin develop 2<&1 "); //代码仓库 一定要使用ssh方式不然每次都得输入密码$res_log = PHP_EOL;$res_log .= $data['user_name'] . ' 在' . date('Y-m-d H:i:s') . '向' . $data['repository']['name'];$res_log .= '项目的' . $data['ref'] . '分支push了' . $data['total_commits_count'] . '个 ';$message = '';if (isset($data['commits']['message'][0])){$message = $data['commits']['message'][0];}elseif (isset($data['commits']['message'])){$message = $data['commits']['message'];}$res_log .= 'commit:' . $message;$res_log .= $res;$res_log .= "pull end -----------------------------------------------------" . PHP_EOL;//保存日志文件路径 注意开启日志写入权限Log::debug('git自动拉去:'.$res_log);if (isset($data['ref']) && $data['total_commits_count'] > 0) {$typeText = "\r\n更新正常\r\n";$res_log .= $typeText;} else {$typeText = "\r\n无提交也更新\r\n";$res_log .= $typeText;}echo $res_log;}

在git远程仓库配置回调地址

在这里插入图片描述

查看触发结果
在这里插入图片描述

在这里插入图片描述