Guest User

Untitled

a guest
Jan 6th, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.73 KB | None | 0 0
  1. import logging
  2. import paramiko
  3.  
  4. class SSH:
  5. def __init__(self):
  6. pass
  7.  
  8. def get_ssh_connection(self, ssh_machine, ssh_username, ssh_password):
  9. """Establishes a ssh connection to execute command.
  10. :param ssh_machine: IP of the machine to which SSH connection to be established.
  11. :param ssh_username: User Name of the machine to which SSH connection to be established..
  12. :param ssh_password: Password of the machine to which SSH connection to be established..
  13. returns connection Object
  14. """
  15. client = paramiko.SSHClient()
  16. client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  17. client.connect(hostname=ssh_machine, username=ssh_username, password=ssh_password, timeout=10)
  18. return client
  19.  
  20. def run_command(self, ssh_username="root", ssh_password="abc123", ssh_machine="localhost", command="ls",
  21. jobid="None", job_details=""):
  22. """Executes a command over a established SSH connectio.
  23. :param ssh_machine: IP of the machine to which SSH connection to be established.
  24. :param ssh_username: User Name of the machine to which SSH connection to be established..
  25. :param ssh_password: Password of the machine to which SSH connection to be established..
  26. returns status of the command executed and Outpuf of the command.
  27. """
  28. conn = self.get_ssh_connection(ssh_machine=ssh_machine, ssh_username=ssh_username, ssh_password=ssh_password)
  29.  
  30. stdin, stdout, stderr = conn.exec_command(command="hostname")
  31. stdoutput = [line for line in stdout]
  32. logging.debug("Job[%s]: Executing: %s on Host: %s" % (jobid, command, stdoutput))
  33.  
  34. stdin, stdout, stderr = conn.exec_command(command=command)
  35. stdoutput = [line for line in stdout]
  36. stderroutput = [line for line in stderr]
  37. for output in stdoutput:
  38. logging.info("Job[%s]: %s" % (jobid, output.strip()))
  39.  
  40. # Check exit code.
  41. logging.debug("Job[%s]:stdout: %s" % (jobid, stdoutput))
  42. logging.debug("Job[%s]:Job details: %s" % (jobid, job_details))
  43. logging.debug("Job[%s]:stderror: %s, job_details: %s" % (jobid, stderroutput, job_details))
  44. logging.info("Job[%s]:Command status: %s" % (jobid, stdout.channel.recv_exit_status()))
  45. if not stdout.channel.recv_exit_status():
  46. logging.info("Job[%s]: Command executed." % jobid)
  47. conn.close()
  48. if not stdoutput:
  49. stdoutput = True
  50. return True, stdoutput
  51. else:
  52. logging.error("Job[%s]: Command failed." % jobid)
  53. for output in stderroutput:
  54. logging.error("Job[%s]: %s" % (jobid, output))
  55. conn.close()
  56. return False, stderroutput
Add Comment
Please, Sign In to add comment