123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # @File : webhooks.py.py
- # @Author: becivells
- #@Contact : becivells@gmail.com
- # @Date : 2017/10/19
- #@Software : PyCharm
- # @Desc :
- import time
- from flask import Flask
- from flask import request
- from core import runcmd
- from core import allow_exec
- from core import allow_path
- from core import getrepo
- from config import HOST
- from config import PORT
- from config import DEBUG
- from config import SYNC_PATH
- from config import GIT_SERVER
- from config import CONF_UPDATE_TIME
- app = Flask(__name__)
- # app.config.update(dict(
- # DEBUG=True,
- # SECRET_KEY='development key'
- # ))
- # app.config.from_envvar('FLASKR_SETTINGS', silent=True)
- #记录git仓库更新间隔时间初始状态状态
- status = {}
- #初始化配置
- repo = getrepo()
- def gettime():
- return time.time()
- #记录如果token不存在ip地址和路径需要更新时初始时间
- confsync = gettime()
- @app.route('/')
- def hello_world():
- return 'Hello World!\n',403
- @app.route('/{SYNC_PATH}/<token>'.format(SYNC_PATH=SYNC_PATH))
- def sync(token):
- ip = request.remote_addr.strip()
- global repo
- if token not in repo:
- if gettime() - confsync > CONF_UPDATE_TIME:
- repo = getrepo()
- if token not in repo:
- #token错误
- return u'Hello %s !!\n'%(ip),403
- if (ip not in repo[token]['ip']) and (ip not in GIT_SERVER):
- #ip 来源错误
- return u'Hello %s !!!\n'%(ip),403
- interval = repo[token]['interval']
- path = repo[token]['path']
- cmd = repo[token]['cmd']
- cmd = ' '.join(cmd.split())#移除多余空格
- user = repo[token]['user']
- name = repo[token]['name']
- if path.endswith('/'):
- syndir = path.split('/')[-2] # 显示同步目录防止出错
- else:
- syndir = path.split('/')[-1] # 显示同步目录防止出错
- if token in status:
- end_time = gettime()
- if end_time - status[token] < interval:
- return u'同步太频繁,请稍后\n\n\n\n'
- status[token]=gettime()
- # 检测是否允许执行此命令执行
- if not allow_exec(cmd):
- return 'the cmd not in exec white list',403
- # 检测是否允许在此目录执行
- if not allow_path(path):
- return 'The path is not allow access',403
- # 执行命令
- tmp = runcmd(cmd, path) + '\n\n'
- # 更改权限
- tmp += runcmd('chown -R {user}:{user} *'.format(user=user), path)
- #显示结果
- showchar ='name: {name}\nsyndir is: {syndir}\n\n{tmp}\n'.format(
- name=name,syndir=syndir,tmp=tmp)
- return showchar
- @app.errorhandler(404)
- def page_error(error):
- return 'Hello World!\n',403
- if __name__ == '__main__':
- app.run(host=HOST,port=PORT,debug=DEBUG)
|