shell_execute.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/python3
  2. import os, io, sys, platform, shutil, time, subprocess, json, datetime
  3. from api.utils.log import myLogger
  4. from api.exception.command_exception import CommandException
  5. from api.utils import const
  6. # This fuction is for running shell commands on container
  7. # cmd_str e.g: "ls -a"
  8. # return string limit: 4000 chars? to do
  9. def execute_command_output(cmd_str):
  10. print(cmd_str)
  11. out_str = subprocess.getoutput(cmd_str)
  12. print(out_str)
  13. return out_str
  14. # This fuction is for running shell commands on host machine
  15. # cmd_str e.g: "ls -a"
  16. # return string limit: 4000 chars
  17. def execute_command_output_all(cmd_str):
  18. myLogger.info_logger("Start to execute cmd: " + cmd_str)
  19. process = subprocess.run(f'nsenter -m -u -i -n -p -t 1 sh -c "{cmd_str}"', capture_output=True, bufsize=65536, check=False, text=True, shell=True)
  20. 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:
  21. return {"code": "0", "result": process.stdout,}
  22. else:
  23. myLogger.info_logger("Failed to execute cmd, output failed result")
  24. myLogger.info_logger(process)
  25. raise CommandException(const.ERROR_SERVER_COMMAND,"Docker returns the original error", process.stderr)
  26. # This fuction is convert container commands to host machine commands
  27. def convert_command(cmd_str):
  28. convert_cmd = ""
  29. if cmd_str == "":
  30. convert_cmd=cmd_str
  31. else:
  32. convert_cmd="nsenter -m -u -i -n -p -t 1 sh -c " + "'"+cmd_str+"'"
  33. return convert_cmd