Gogs 配置ssh访问

1、指定用户目录生成ssh公钥

查看Nginx执行用户

为执行用户生成ssh公钥

cd /home/www/.ssh
ssh-keygen -t ed25519 -f id_rsa_ed25519 -C "mail@domain.com"
#没有 ed25519 算法时使用 rsa 算法
#ssh-keygen -t rsa -b 4096 -f id_rsa_www  -C "mail@domain.com"

2、设置.ssh/config文件

Host ip/host
    User root
    IdentityFile /home/www/.ssh/id_rsa_www
    IdentitiesOnly yes

3、使用ssh模式clone仓库

一定要指定执行的用户

sudo -u www git clone root@host:/username/git.git

4、使用WebHook勾子同步仓库

<?php
/**
 * 自动更新钩子支持gogs,gitee
 * 修改密钥及部署分支
 **/
//运行目录
define('RUN_DIR', __DIR__);
//仓库根目录
define('PROJECT_DIR', dirname(dirname(__DIR__)));
//密钥信息
define('ACCESS_SECRET', '-----');
//要部署的分支
define('BRANCH', 'master');
//仓库源(gogs,gitee)
define('GIT_SERVER', 'gogs');

//以流的方式读取
$requestBody = file_get_contents("php://input");
if (empty($requestBody)) {
    die('send fail');
}
// 日志记录
function git_log($str){
    if(!is_dir(RUN_DIR . '/log')){
        mkdir(RUN_DIR . '/log', 0770, true);
    }
    $fs = fopen(RUN_DIR . '/log/hook_'.date('Ymd').'.log', 'a');
    if($fs){
        fwrite($fs,  $str. PHP_EOL);
        fclose($fs);
    }
}
//签名内容(不同仓库源内容不同)
$secret_post = '';
$token       = -1;
switch (GIT_SERVER) {
    case 'gogs':
        $secret_post = $_SERVER['HTTP_X_GOGS_SIGNATURE'];
        //加密内容
        $token       = hash_hmac('sha256', $requestBody, ACCESS_SECRET);
        $requestBody = json_decode($requestBody,true);
        break;
    case 'gitee':
        $requestBody = json_decode($requestBody,true);
        $secret_post = $requestBody['sign'];
        $token       = base64_encode(hash_hmac('sha256', $requestBody['timestamp'] . ACCESS_SECRET, ACCESS_SECRET, true));
        break;
}
$branch      = str_replace('refs/heads/', '', $requestBody['ref']);
$requestBody = null;
// 把请求的IP和时间写进log
git_log('==Begin=='. PHP_EOL.'Request on [' . date("Y-m-d H:i:s") . '] from [' . $_SERVER['REMOTE_ADDR'] . '] branch ['.$branch.']');
// 验证token 有错就写进日志并退出
if ($token !== $secret_post) {
    git_log(" Invalid token [{$token}]-{$secret_post}");
    header("HTTP/1.1 404 Not Found");
    header("Status: 404 Not Found");
    exit(0);
}
//检测是否要部署的分支
if($branch == BRANCH) {
    git_log('=== Update Start ===');
    // 执行shell命令并把返回信息写进日志
    exec('cd '.PROJECT_DIR.' && git reset --hard HEAD && git pull origin '.BRANCH.' 2<&1;',$output);
    git_log('Info:' . print_r($output, true). PHP_EOL.'=== Update End ===');
}