remotehost.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # Host class
  2. # Copyright (c) 2016, Qualcomm Atheros, Inc.
  3. #
  4. # This software may be distributed under the terms of the BSD license.
  5. # See README for more details.
  6. import logging
  7. import subprocess
  8. import threading
  9. logger = logging.getLogger()
  10. def execute_thread(command, reply):
  11. cmd = ' '.join(command)
  12. logger.debug("thread run: " + cmd)
  13. try:
  14. status = 0;
  15. buf = subprocess.check_output(command, stderr=subprocess.STDOUT)
  16. except subprocess.CalledProcessError as e:
  17. status = e.returncode
  18. buf = e.output
  19. logger.debug("thread cmd: " + cmd)
  20. logger.debug("thread exit status: " + str(status))
  21. logger.debug("thread exit buf: " + str(buf))
  22. reply.append(status)
  23. reply.append(buf)
  24. class Host():
  25. def __init__(self, host=None, ifname=None, port=None, name="", user="root"):
  26. self.host = host
  27. self.name = name
  28. self.user = user
  29. self.ifname = ifname
  30. self.port = port
  31. if self.name == "" and host != None:
  32. self.name = host
  33. def local_execute(self, command):
  34. logger.debug("execute: " + str(command))
  35. try:
  36. status = 0;
  37. buf = subprocess.check_output(command, stderr=subprocess.STDOUT)
  38. except subprocess.CalledProcessError as e:
  39. status = e.returncode
  40. buf = e.output
  41. logger.debug("status: " + str(status))
  42. logger.debug("buf: " + str(buf))
  43. return status, buf
  44. def execute(self, command):
  45. if self.host is None:
  46. return self.local_execute(command)
  47. cmd = ["ssh", self.user + "@" + self.host, ' '.join(command)]
  48. _cmd = self.name + " execute: " + ' '.join(cmd)
  49. logger.debug(_cmd)
  50. try:
  51. status = 0
  52. buf = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  53. except subprocess.CalledProcessError as e:
  54. status = e.returncode
  55. buf = e.output
  56. logger.debug(self.name + " status: " + str(status))
  57. logger.debug(self.name + " buf: " + str(buf))
  58. return status, buf
  59. # async execute
  60. def execute_run(self, command, res):
  61. if self.host is None:
  62. cmd = command
  63. else:
  64. cmd = ["ssh", self.user + "@" + self.host, ' '.join(command)]
  65. _cmd = self.name + " execute_run: " + ' '.join(cmd)
  66. logger.debug(_cmd)
  67. t = threading.Thread(target = execute_thread, args=(cmd, res))
  68. t.start()
  69. return t
  70. def wait_execute_complete(self, t, wait=None):
  71. if wait == None:
  72. wait_str = "infinite"
  73. else:
  74. wait_str = str(wait) + "s"
  75. logger.debug(self.name + " wait_execute_complete(" + wait_str + "): ")
  76. if t.isAlive():
  77. t.join(wait)