shell_execute.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/bin/python3
  2. import os, io, sys, platform, shutil, time, subprocess, json, datetime
  3. # 执行Shell命令,处理报错和超时,并有返回值
  4. def execute_Command(cmd_str, timeout=60, timeinner=3, retry=True):
  5. print(cmd_str)
  6. time_out = 0
  7. status = False
  8. while time_out < timeout:
  9. out_str = subprocess.getstatusoutput(cmd_str)
  10. print(out_str)
  11. if out_str[0] == 0 and out_str[1].find('ERROR') == -1 and out_str[1].find('error') == -1:
  12. status = True
  13. print('\nExecute successfully')
  14. break
  15. elif retry:
  16. print('\nTry again')
  17. time.sleep(timeinner)
  18. time_out = time_out + timeinner
  19. else:
  20. time_out = timeout
  21. if not status:
  22. print('\n此次任务执行有异常,请仔细排查')
  23. # 执行Shell命令,处理报错和超时,并有返回值
  24. def execute_CommandReturn(cmd_str, timeout=30, timeinner=3):
  25. print(cmd_str)
  26. time_out = 0
  27. while time_out < timeout:
  28. out_str = subprocess.getstatusoutput(cmd_str)
  29. print(out_str)
  30. if out_str[0] == 0 and out_str[1].find('ERROR') == -1 and out_str[1].find('error') == -1:
  31. # 去掉\n和"
  32. # 返回值是元组,不能修改,需要赋值给变量
  33. temp_str = out_str[1]
  34. temp_str = temp_str.strip('\n')
  35. temp_str = temp_str.strip('"')
  36. time_out = timeout
  37. return temp_str
  38. else:
  39. time.sleep(timeinner)
  40. time_out = time_out + timeinner
  41. print('\n此次任务执行失败,请根据下面错误原因排查:')
  42. print(out_str)
  43. def execute_command_output(cmd_str):
  44. print(cmd_str)
  45. out_str = subprocess.getoutput(cmd_str)
  46. print(out_str)
  47. return out_str
  48. # cmd_str: 执行的command命令 times:如果不成功的重复次数
  49. def execute_command_output_all(cmd_str, max_time = 3):
  50. print("start to excute cmd: " + cmd_str)
  51. excutetime = 0
  52. while excutetime < max_time:
  53. process = subprocess.run(cmd_str, shell=True, stdout=subprocess.PIPE, universal_newlines=True)
  54. if process.returncode == 0:
  55. return process.stdout
  56. else:
  57. excutetime = excutetime + 1
  58. return "command excute failed, please check your command!"