sshcmd2node.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/local/bin/python
  2. import subprocess, sys, os
  3. from threading import Thread
  4. from re import search
  5. # Node class
  6. class Node(Thread):
  7. # Constructor
  8. def __init__(self, name, location, sshcmd):
  9. # Fork the thread first thing
  10. Thread.__init__(self)
  11. # Variables initialization
  12. self.hostname = name
  13. self.location = location
  14. self.up = False
  15. self.cmd = sshcmd
  16. # Run method called on Thread start: check if host is up and run sshcmd
  17. def run(self) :
  18. if self.isup() :
  19. self.up = True
  20. self.cmdresult=self.sshcommand(self.cmd)
  21. # Ping the host to see if it's up
  22. def isup(self):
  23. # Is the host up?
  24. ping = os.popen("ping -w1 -c1 " + self.hostname, "r")
  25. if "0 received" in ping.read():
  26. return False
  27. else:
  28. return True
  29. # Run a command within an ssh connection to the node.
  30. # Return a tuple (exit status 0/1, out/err)
  31. # There should be a better way to do this... Something like thowing exceptions
  32. # and collecting them from the calling program...
  33. # FIXME: doesn't always catch errors from the bash command
  34. def sshcommand(self, command):
  35. if self.isup():
  36. cmd = subprocess.Popen( ["ssh", "%s" % self.hostname, command],
  37. shell = False,
  38. stdout = subprocess.PIPE,
  39. stderr = subprocess.PIPE )
  40. # This is not a good way to look for errors
  41. out, err = cmd.communicate()
  42. exitcode=cmd.returncode
  43. return (exitcode, out.strip().split('\n'), err)
  44. else:
  45. return (1, self.hostname + " is down")
  46. ## End Node class