shell_execute.py 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. #!/usr/bin/python3
  2. import os, io, sys, platform, shutil, time, subprocess, json, datetime
  3. from api.utils.common_log import myLogger
  4. def execute_command_output(cmd_str):
  5. print(cmd_str)
  6. out_str = subprocess.getoutput(cmd_str)
  7. print(out_str)
  8. return out_str
  9. # cmd_str: 执行的command命令 times:如果不成功的重复次数
  10. def execute_command_output_all(cmd_str, max_time = 3):
  11. myLogger.info_logger("Start to execute cmd: " + cmd_str)
  12. execute_time = 0
  13. while execute_time < max_time:
  14. process = subprocess.run(convert_command(cmd_str), capture_output=True, check=True, text=True, shell=True)
  15. if process.returncode == 0:
  16. return {"code": "0", "result": process.stdout,}
  17. else:
  18. execute_time = execute_time + 1
  19. myLogger.error_logger("Command execute failed Commend: " + cmd_str)
  20. return {"code": "-1", "result": "command execute failed, please check your command!"}
  21. def convert_command(cmd_str):
  22. convert_cmd = ""
  23. if cmd_str == "":
  24. convert_cmd=cmd_str
  25. else:
  26. convert_cmd="f nsenter -m -u -i -n -p -t 1 sh -c " +cmd_str
  27. return convert_cmd