websoft9/appmanage/api/utils/shell_execute.py

37 lines
1.4 KiB
Python
Raw Normal View History

2023-02-22 10:44:15 +08:00
#!/usr/bin/python3
2023-02-21 14:21:53 +08:00
import os, io, sys, platform, shutil, time, subprocess, json, datetime
2023-03-15 17:55:05 +08:00
from api.utils.common_log import myLogger
2023-04-14 10:51:29 +08:00
from api.exception.command_exception import CommandException
2023-04-14 16:41:43 +08:00
from api.utils import const
2023-02-21 14:21:53 +08:00
2023-02-22 11:29:06 +08:00
def execute_command_output(cmd_str):
print(cmd_str)
2023-02-22 11:29:14 +08:00
out_str = subprocess.getoutput(cmd_str)
2023-02-22 11:29:06 +08:00
print(out_str)
return out_str
2023-02-22 14:43:36 +08:00
# cmd_str: 执行的command命令 times如果不成功的重复次数
2023-04-14 16:41:43 +08:00
def execute_command_output_all(cmd_str, max_time = 2):
2023-02-22 14:43:36 +08:00
2023-03-15 17:55:05 +08:00
myLogger.info_logger("Start to execute cmd: " + cmd_str)
execute_time = 0
while execute_time < max_time:
2023-04-14 10:51:29 +08:00
2023-03-24 15:15:57 +08:00
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)
2023-03-24 14:58:10 +08:00
2023-04-14 10:51:29 +08:00
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:
2023-02-22 14:50:10 +08:00
return {"code": "0", "result": process.stdout,}
2023-02-22 14:43:36 +08:00
else:
2023-03-15 17:55:05 +08:00
execute_time = execute_time + 1
2023-04-14 16:41:43 +08:00
if execute_time > 2:
raise CommandException(const.ERROR_SERVER_COMMAND,"Docker returns the original error",process.stdout)
2023-03-02 14:56:08 +08:00
def convert_command(cmd_str):
convert_cmd = ""
if cmd_str == "":
convert_cmd=cmd_str
else:
2023-03-24 14:02:24 +08:00
convert_cmd="nsenter -m -u -i -n -p -t 1 sh -c " + "'"+cmd_str+"'"
2023-03-02 14:56:08 +08:00
return convert_cmd