webhooks.py 2.7 KB

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