core.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # @File : core.py
  4. # @Author: becivells
  5. #@Contact : becivells@gmail.com
  6. # @Date : 2017/10/19
  7. #@Software : PyCharm
  8. # @Desc :
  9. import re
  10. import tempfile
  11. import subprocess
  12. from config import repo
  13. from config import EXEC_WHITE_LIST
  14. from config import PATH_WHITE_LIST
  15. from conf.confapi import getconf
  16. from db.db import get_dbconf
  17. def runcmd(cmd,path):
  18. out_temp = tempfile.SpooledTemporaryFile(max_size=10 * 1000)
  19. try:
  20. fileno = out_temp.fileno()
  21. p = subprocess.Popen(cmd, shell=True,cwd=path, stdout=fileno, stderr=fileno)
  22. p.wait()
  23. out_temp.seek(0)
  24. return out_temp.read()
  25. except Exception as e:
  26. return str(e)
  27. finally:
  28. if out_temp:
  29. out_temp.close()
  30. def allow_exec(cmd):
  31. '''
  32. 白名单函数允许指定命令运行并且限制长度
  33. :param cmd:
  34. :return:
  35. '''
  36. cmd = ' '.join(cmd.split()) #移除多余空格
  37. if len(cmd) > 100: #限制长度
  38. return False
  39. for whitecmd in EXEC_WHITE_LIST:
  40. result = re.findall(whitecmd,cmd)
  41. if result and cmd == result[0]:
  42. return True
  43. return False
  44. def allow_path(path):
  45. '''
  46. 限制路径
  47. :param path:
  48. :return:
  49. '''
  50. path = path.strip()
  51. for whitepath in PATH_WHITE_LIST:
  52. result = re.findall(whitepath,path)
  53. if result and path == result[0]:
  54. return True
  55. return False
  56. def getrepo():
  57. '''
  58. 更新配置文件
  59. :return:
  60. '''
  61. repo.update(getconf())
  62. repo.update(get_dbconf())
  63. return repo