宝塔利用Git + WebHook 实现与码云同步
一、给Linux服务器安装Git
1、git宝塔面板自带,直接安装就好

2、把上图的ssh-rsa全部字符串添加到码云部署项目公钥设置里

这样git就配置好了,为了避免每次都拉代码的时候都需要输入账号密码,打开git终端可以做如下配置
// Git全局配置用户名与邮箱
git config --global user.name "username"
git config --global user.email "your@email.com"
// 避免每次拉代码都需要输入账号密码 作如下配置
git config --global credential.helper store
// 会生成.gitconfig 的文件,查看
cat .gitconfig // 报错cat: .gitconfig : No such file or directory
cat ~/.gitconfig // 显示内容
[user]
name = username
email = your@email.com
[credential]
helper = store
// 第一次pull会提示输入用户名密码,后续就不会提示输入密码了
[root@VM_0_7_centos ~]# git pull
Username for 'https://gitee.com': your@email.com
Password for 'https://xxxx@xxxx.com@gitee.com':yourPassword(看不到输入内容)
二、配置WebHook
1、在宝塔面板中找到WebHook安装,添加一个Hook

2、选择新添加的Hook,点击编辑,把如下代码放到执行脚本中
#!/bin/bash
echo ""
#输出当前时间
date --date='0 days ago' "+%Y-%m-%d %H:%M:%S"
echo "Start"
#判断宝塔WebHook参数是否存在
if [ ! -n "$1" ];
then
echo "param参数错误"
echo "End"
exit
fi
#git项目路径($1是param后面的参数,指向你的服务器的目录)
gitPath="/www/wwwroot/web/$1"
#git 网址 (替换成你的git地址,可选择https方式或者ssh方式)
gitHttp="https://gitee.com/xingdong_1/test.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
#拉取最新的项目文件
sudo git reset --hard origin/master
sudo git pull
#设置目录权限
sudo chown -R www:www $gitPath
echo "拉取最新文件"
echo "End"
exit
else
echo "该项目路径不存在"
echo "End"
exit
fi
添加shell命令后需重启宝塔
点击查看秘钥,会获得一个地址
http: //ip:端口/hook?access_key=秘钥¶m=git项目名
把拼接好的地址添加到码云上

注:网站项目名与码云项目名要一致