range

If there were you, the world would be just right

安装python3:

安装相关包

yum install zlib zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc

下载python3的源码包

wget https://www.python.org/ftp/python/3.6.4/Python-3.6.4.tar.xz

解压python3源码包

xz -d Python-3.6.4.tar.xz
tar -xf Python-3.6.4.tar

编译安装

cd Python-3.6.4
./configure prefix=/usr/local/python3
make && make install

添加软链接

ln -s /usr/local/python3/bin/python3.6 /usr/bin/python3
ln -s /usr/local/python3/bin/pip3 /usr/bin/pip3

安装Web.py(接收器)

pip3 install --upgrade pip

pip3 install web.py

设置gogs-web钩子
143918.png

编写脚本代码接收信号并更新git

#!/usr/bin/python3
#coding=utf-8
import web
import json
import os

urls = (
     '/', 'web_exec'
)
app = web.application(urls, globals())
# 获取当前日志路径 
log_path = os.getcwd()

class web_exec:
    def POST(self):
        # inp为str
        inp = web.input().payload
        # data为dict
        data = json.loads(inp)

        # 当前推送获取的分支
        ref = data['ref']

        # 只更新master 分支内容
        if( ref!='refs/heads/master' ):
            return

        msg = '------------------------------------ start ------------------------------------'
        self.write_log_to_file(msg)

        sys_msg = "当前推送获取的分支:"+ref
        self.write_log_to_file(sys_msg)

        # 当前更新版本
        after_version = data['after']
        sys_msg = "当前更新版本:"+after_version
        self.write_log_to_file(sys_msg)

        # 当前版本推送人
        username = data['pusher']['username']
        sys_msg = "当前版本推送人:"+username
        self.write_log_to_file(sys_msg)        

        # 当前项目
        name = data['repository']['name']
        sys_msg = "当前执行更新项目:"+name
        self.write_log_to_file(sys_msg)

        # 进入对应的目录
        path = '/data/web/' + name + '/'
        sys_msg = "执行进入目录:"+path
        self.write_log_to_file(sys_msg)

        os.chdir(path)

        # 取回更新后
        sys = '/usr/bin/git fetch --all'
        sys_msg = "执行git fetch:"+sys
        self.write_log_to_file(sys_msg)

        os.system(sys)

        # 执行更新版本
        sys = '/usr/bin/git reset --hard ' + after_version;
        sys_msg = "最终执行更新脚本命令:"+sys
        self.write_log_to_file(sys_msg)

        msg = '------------------------------------ end ------------------------------------'
        self.write_log_to_file(msg)

        return os.system(sys)

    # 记录日志信息
    def write_log_to_file(self,msg):
        print('开始写入数据 ====> ' + str(msg))
        with open(log_path + 'git_update.log', 'a', encoding='UTF-8') as f:
            f.write(json.dumps(msg, ensure_ascii=False) + '\n')
            f.close()

if __name__ == "__main__":
    app.run()

运行脚本

python3 web_gz.py

推送git内容
push38.png

查看脚本打印
11.png

进入项目目录,查看是否有拉取到内容
73016.png

end!!


添加新评论 »

在这里输入你的评论...