php-fpm内shell_exec执行命令实现WebHooks代码拉取

WebHook 简介

摘自gitee:WebHook 功能是帮助用户 push 代码后,自动回调一个您设定的 http 地址。
这是一个通用的解决方案,用户可以自己根据不同的需求,来编写自己的脚本程序(比如发邮件,自动部署等)。

测试环境

  • CentOS Linux release 8.2.2004 (Core) cat /etc/redhat-release
  • PHP 7.4.21 (cli) (built: Jul 14 2021 16:55:00) ( NTS ) php -v

php代码部分

/**
 * 拉取代码
 * @desc 从仓库拉取最新代码
 * @return array
 * @throws Exception
 */
function pull(): array
{
    // 代码拉取(路径替换成你自己的)
    $cmd = 'sudo cd /www/wwwroot/movie.iyuu.cn; sudo git pull';
    if (function_exists('shell_exec'))
    {
        $stdout = shell_exec($cmd);
        if ($stdout === null) {
            $msg = '当前用户无权限执行命令,请编辑/etc/sudoers,添加(www     ALL=(ALL)   NOPASSWD:/usr/bin/git)';
            throw new Exception(shell_exec("id -a") . PHP_EOL . $msg, 3);
        }
    } else {
        throw new Exception('shell_exec函数不可用', 3);
    }

    return ['state' => $stdout];
}

以上函数实现检测shell_exec是否被禁用;如果命令执行失败,会输出当前用户组,并提示编辑/etc/sudoers
可以配置你仓库的webHooks密钥,在收到http请求密钥验证通过之后,调用以上函数即可(把路径/www/wwwroot/movie.iyuu.cn替换为你自己的)。

Centos系统配置/etc/sudoers

如果不清楚命令的执行文件位置,可以用which命令查看。

root    ALL=(ALL)     ALL
# 新增:允许www用户无需密码执行的命令
www     ALL=(ALL)   NOPASSWD:/usr/bin/crontab,/usr/bin/git

/etc/sudoers的更多配置,可以搜索查询。

报错处理

sudo: pam_open_session: System error
sudo: policy plugin failed session initialization

如果报以上错误,说明用户密码过期,执行以下命令:
chage -M 99999 www

最后修改:2022 年 02 月 02 日 06 : 00 PM
如果觉得我的文章对你有用,请随意赞赏

发表评论