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.60 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_sudo_command(self, ssh_username="root", ssh_password="abc123", ssh_machine="localhost", command="ls",
  21. jobid="None"):
  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 Output of the command.
  27. """
  28. conn = self.get_ssh_connection(ssh_machine=ssh_machine, ssh_username=ssh_username, ssh_password=ssh_password)
  29. command = "sudo -S -p '' %s" % command
  30. logging.info("Job[%s]: Executing: %s" % (jobid, command))
  31. stdin, stdout, stderr = conn.exec_command(command=command)
  32. stdin.write(ssh_password + "\n")
  33. stdin.flush()
  34. stdoutput = [line for line in stdout]
  35. stderroutput = [line for line in stderr]
  36. for output in stdoutput:
  37. logging.info("Job[%s]: %s" % (jobid, output.strip()))
  38. # Check exit code.
  39. logging.debug("Job[%s]:stdout: %s" % (jobid, stdoutput))
  40. logging.debug("Job[%s]:stderror: %s" % (jobid, stderroutput))
  41. logging.info("Job[%s]:Command status: %s" % (jobid, stdout.channel.recv_exit_status()))
  42. if not stdout.channel.recv_exit_status():
  43. logging.info("Job[%s]: Command executed." % jobid)
  44. conn.close()
  45. if not stdoutput:
  46. stdoutput = True
  47. return True, stdoutput
  48. else:
  49. logging.error("Job[%s]: Command failed." % jobid)
  50. for output in stderroutput:
  51. logging.error("Job[%s]: %s" % (jobid, output))
  52. conn.close()
  53. return False, stderroutput
Add Comment
Please, Sign In to add comment