core.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. def runcmd(cmd,path):
  16. out_temp = tempfile.SpooledTemporaryFile(max_size=10 * 1000)
  17. try:
  18. fileno = out_temp.fileno()
  19. p = subprocess.Popen(cmd, shell=True,cwd=path, stdout=fileno, stderr=fileno)
  20. p.wait()
  21. out_temp.seek(0)
  22. return out_temp.read()
  23. except Exception as e:
  24. return str(e)
  25. finally:
  26. if out_temp:
  27. out_temp.close()
  28. def allow_exec(cmd):
  29. '''
  30. 白名单函数允许指定命令运行并且限制长度
  31. :param cmd:
  32. :return:
  33. '''
  34. cmd = ' '.join(cmd.split()) #移除多余空格
  35. if len(cmd) > 100: #限制长度
  36. return False
  37. for whitecmd in EXEC_WHITE_LIST:
  38. result = re.findall(whitecmd,cmd)
  39. if result and cmd == result[0]:
  40. return True
  41. return False
  42. def allow_path(path):
  43. '''
  44. 限制路径
  45. :param path:
  46. :return:
  47. '''
  48. path = path.strip()
  49. for whitepath in PATH_WHITE_LIST:
  50. result = re.findall(whitepath,path)
  51. if result and path == result[0]:
  52. return True
  53. return False
  54. def getrepo():
  55. '''
  56. 更新配置文件
  57. :return:
  58. '''
  59. return repo