1. 配置服务器上的git环境
bash
# 在项目目录下执行以下命令, 将码云仓库的代码拉取到服务器项目目录上
git clone https://gitee.com/your_username/your_repository.git
# 配置记住密码
git config --global credential.helper store
# 生成 SSH 密钥, 一路回车,复制下图内的公钥内容添加到码云内
ssh-keygen -t rsa


2. 宝塔安装 WebHook 插件,并完成脚本配置
::: tip 1.宝塔面板内软件商店搜索 WebHook 安装
2.安装完成后,点击 WebHook 进入配置页面
3.点击右上角的"添加 WebHook"按钮
:::
::: details 脚本代码(记得脚本文件中的项目目录、git 地址、git 分支名替换成自己的)
bash
#!/bin/bash
echo ""
# 输出当前时间
date --date='0 days ago' "+%Y-%m-%d %H:%M:%S"
echo "Start"
# git 分支名称
branch="dist"
# git 项目路径
gitPath="/www/wwwroot/huashengmi"
# git 仓库地址
gitHttp="https://gitee.com/xxx/peanut-vitepress.git"
echo "Web站点路径:$gitPath"
# 判断项目路径是否存在
if [ -d "$gitPath" ]; then
cd $gitPath
# 判断是否存在 git 目录
if [ ! -d ".git" ]; then
echo "在该目录下克隆 git"
sudo git clone $gitHttp gittemp
sudo mv gittemp/.git .
sudo rm -rf gittemp
fi
echo "拉取最新的项目文件"
# 获取远程分支的最新 SHA 值
latest_sha=$(sudo git ls-remote $gitHttp refs/heads/$branch | awk '{print $1}')
echo "最新的SHA值为: $latest_sha"
# 强制更新为远程分支的最新版本
sudo git fetch --all
sudo git reset --hard origin/$branch
sudo git pull --force origin $branch
echo "设置目录权限"
sudo chown -R www:www $gitPath
echo "End"
exit
else
echo "该项目路径不存在"
echo "新建项目目录"
mkdir $gitPath
cd $gitPath
# 判断是否存在 git 目录
if [ ! -d ".git" ]; then
echo "在该目录下克隆 git"
sudo git clone $gitHttp gittemp
sudo mv gittemp/.git .
sudo rm -rf gittemp
fi
echo "拉取最新的项目文件"
# 获取远程分支的最新 SHA 值
latest_sha=$(sudo git ls-remote $gitHttp refs/heads/$branch | awk '{print $1}')
echo "最新的SHA值为: $latest_sha"
# 强制更新为远程分支的最新版本
sudo git fetch --all
sudo git reset --hard origin/$branch
sudo git pull --force origin $branch
echo "设置目录权限"
sudo chown -R www:www $gitPath
echo "End"
exit
fi
:::


3. 配置码云仓库的 WebHook

4. 测试 WebHook
码云仓库随意改个文件保存一下, 生成新的提交记录, 看云服务器上有没有同步更新