shell_execute.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536
  1. #!/usr/bin/python3
  2. import os, io, sys, platform, shutil, time, subprocess, json, datetime
  3. from api.utils.common_log import myLogger
  4. from api.exception.command_exception import CommandException
  5. from api.utils import const
  6. def execute_command_output(cmd_str):
  7. print(cmd_str)
  8. out_str = subprocess.getoutput(cmd_str)
  9. print(out_str)
  10. return out_str
  11. # cmd_str: 执行的command命令 times:如果不成功的重复次数
  12. def execute_command_output_all(cmd_str, max_time = 2):
  13. myLogger.info_logger("Start to execute cmd: " + cmd_str)
  14. execute_time = 0
  15. while execute_time < max_time:
  16. process = subprocess.run(f'nsenter -m -u -i -n -p -t 1 sh -c "{cmd_str}"', capture_output=True, check=False, text=True, shell=True)
  17. if process.returncode == 0 and 'Fail' not in process.stdout and 'fail' not in process.stdout and 'Error' not in process.stdout and 'error' not in process.stdout:
  18. return {"code": "0", "result": process.stdout,}
  19. else:
  20. execute_time = execute_time + 1
  21. if execute_time > 2:
  22. raise CommandException(const.ERROR_SERVER_COMMAND,"Docker returns the original error",process.stdout)
  23. def convert_command(cmd_str):
  24. convert_cmd = ""
  25. if cmd_str == "":
  26. convert_cmd=cmd_str
  27. else:
  28. convert_cmd="nsenter -m -u -i -n -p -t 1 sh -c " + "'"+cmd_str+"'"
  29. return convert_cmd