shell_execute.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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