webhooks.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # @File : webhooks.py.py
  4. # @Author: becivells
  5. #@Contact : becivells@gmail.com
  6. # @Date : 2017/10/19
  7. #@Software : PyCharm
  8. # @Desc :
  9. import time
  10. from flask import Flask
  11. from flask import request
  12. from core import runcmd
  13. from core import allow_exec
  14. from core import allow_path
  15. from core import getrepo
  16. from config import HOST
  17. from config import PORT
  18. from config import DEBUG
  19. from config import SYNC_PATH
  20. from config import GIT_SERVER
  21. app = Flask(__name__)
  22. # app.config.update(dict(
  23. # DEBUG=True,
  24. # SECRET_KEY='development key'
  25. # ))
  26. # app.config.from_envvar('FLASKR_SETTINGS', silent=True)
  27. #记录git仓库更新间隔时间初始状态状态
  28. status = {}
  29. #初始化配置
  30. repo = getrepo()
  31. def gettime():
  32. return time.time()
  33. #记录如果token不存在ip地址和路径需要更新时初始时间
  34. confsync = gettime()
  35. @app.route('/')
  36. def hello_world():
  37. return 'Hello World!\n',403
  38. @app.route('/{SYNC_PATH}/<token>'.format(SYNC_PATH=SYNC_PATH))
  39. def sync(token):
  40. ip = request.remote_addr.strip()
  41. global repo
  42. if token not in repo:
  43. #token错误
  44. return u'Hello %s token error !!\n'%(ip),403
  45. if (ip not in repo[token]['ip']) and (ip not in GIT_SERVER):
  46. #ip 来源错误
  47. return u'Hello %s ip error!!!\n'%(ip),403
  48. interval = repo[token]['interval']
  49. path = repo[token]['path']
  50. cmd = repo[token]['cmd']
  51. cmd = ' '.join(cmd.split())#移除多余空格
  52. user = repo[token]['user']
  53. name = repo[token]['name']
  54. if path.endswith('/'):
  55. syndir = path.split('/')[-2] # 显示同步目录防止出错
  56. else:
  57. syndir = path.split('/')[-1] # 显示同步目录防止出错
  58. if token in status:
  59. end_time = gettime()
  60. if end_time - status[token] < interval:
  61. return u'同步太频繁,请稍后\n\n\n\n'
  62. status[token]=gettime()
  63. # 检测是否允许执行此命令执行
  64. if not allow_exec(cmd):
  65. return 'the cmd not in exec white list',403
  66. # 检测是否允许在此目录执行
  67. if not allow_path(path):
  68. return 'The path is not allow access',403
  69. # 执行命令
  70. tmp = runcmd(cmd, path)
  71. # 更改权限
  72. #显示结果
  73. showchar ='name: {name}\nsyndir is: {syndir}\n\n{tmp}\n'.format(
  74. name=name,syndir=syndir,tmp=tmp)
  75. return showchar
  76. @app.errorhandler(404)
  77. def page_error(error):
  78. return 'Hello World!\n',403
  79. if __name__ == '__main__':
  80. app.run(host=HOST,port=PORT,debug=DEBUG)