remotehost.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. try:
  12. status = 0;
  13. buf = subprocess.check_output(command, stderr=subprocess.STDOUT)
  14. except subprocess.CalledProcessError as e:
  15. status = e.returncode
  16. buf = e.output
  17. cmd = ""
  18. for c in command:
  19. cmd = cmd + " " + c
  20. logger.debug("thread cmd: " + cmd)
  21. logger.debug("thread exit status: " + str(status))
  22. logger.debug("thread exit buf: " + str(buf))
  23. reply.append(status)
  24. reply.append(buf)
  25. class Host():
  26. def __init__(self, host=None, ifname=None, port=None, name="", user="root"):
  27. self.host = host
  28. self.name = name
  29. self.user = user
  30. self.ifname = ifname
  31. self.port = port
  32. if self.name == "" and host != None:
  33. self.name = host
  34. def local_execute(self, command):
  35. logger.debug("execute: " + str(command))
  36. try:
  37. status = 0;
  38. buf = subprocess.check_output(command, stderr=subprocess.STDOUT)
  39. except subprocess.CalledProcessError as e:
  40. status = e.returncode
  41. buf = e.output
  42. logger.debug("status: " + str(status))
  43. logger.debug("buf: " + str(buf))
  44. return status, buf
  45. def execute(self, command):
  46. if self.host is None:
  47. return self.local_execute(command)
  48. cmd = ["ssh", self.user + "@" + self.host, ' '.join(command)]
  49. _cmd = self.name + " execute: "
  50. for c in cmd:
  51. _cmd = _cmd + " " + c
  52. logger.debug(_cmd)
  53. try:
  54. status = 0
  55. buf = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  56. except subprocess.CalledProcessError as e:
  57. status = e.returncode
  58. buf = e.output
  59. logger.debug(self.name + " status: " + str(status))
  60. logger.debug(self.name + " buf: " + str(buf))
  61. return status, buf
  62. # async execute
  63. def execute_run(self, command, res):
  64. if self.host is None:
  65. cmd = command
  66. else:
  67. cmd = ["ssh", self.user + "@" + self.host, ' '.join(command)]
  68. _cmd = self.name + " execute_run: "
  69. for c in cmd:
  70. _cmd = _cmd + " " + c
  71. logger.debug(_cmd)
  72. t = threading.Thread(target = execute_thread, args=(cmd, res))
  73. t.start()
  74. return t
  75. def wait_execute_complete(self, t, wait=None):
  76. if wait == None:
  77. wait_str = "infinite"
  78. else:
  79. wait_str = str(wait) + "s"
  80. logger.debug(self.name + " wait_execute_complete(" + wait_str + "): ")
  81. if t.isAlive():
  82. t.join(wait)