Guest User

Untitled

a guest
May 8th, 2018
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. import paramiko
  2. ssh = paramiko.SSHClient()
  3. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  4. ssh.connect('host', username='loginname')
  5. stdin, stdout, stderr = ssh.exec_command("pwd")
  6. stdout.readlines()
  7.  
  8. Traceback (most recent call last):
  9. File "audit.py", line 7, in <module>
  10. ssh.connect('host', username='loginname')
  11. File "/usr/lib/python2.6/site-packages/paramiko/client.py", line 338, in connect
  12. self._auth(username, password, pkey, key_filenames, allow_agent, look_for_keys)
  13. File "/usr/lib/python2.6/site-packages/paramiko/client.py", line 520, in _auth
  14. raise SSHException('No authentication methods available')
  15.  
  16. #!/usr/bin/python
  17.  
  18. from StringIO import StringIO
  19. import paramiko
  20.  
  21. class SshClient:
  22. "A wrapper of paramiko.SSHClient"
  23. TIMEOUT = 4
  24.  
  25. def __init__(self, host, port, username, password, key=None, passphrase=None):
  26. self.username = username
  27. self.password = password
  28. self.client = paramiko.SSHClient()
  29. self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  30. if key is not None:
  31. key = paramiko.RSAKey.from_private_key(StringIO(key), password=passphrase)
  32. self.client.connect(host, port, username=username, password=password, pkey=key, timeout=self.TIMEOUT)
  33.  
  34. def close(self):
  35. if self.client is not None:
  36. self.client.close()
  37. self.client = None
  38.  
  39. def execute(self, command, sudo=False):
  40. feed_password = False
  41. if sudo and self.username != "root":
  42. command = "sudo -S -p '' %s" % command
  43. feed_password = self.password is not None and len(self.password) > 0
  44. stdin, stdout, stderr = self.client.exec_command(command)
  45. if feed_password:
  46. stdin.write(self.password + "n")
  47. stdin.flush()
  48. return {'out': stdout.readlines(),
  49. 'err': stderr.readlines(),
  50. 'retval': stdout.channel.recv_exit_status()}
  51.  
  52. if __name__ == "__main__":
  53. client = SshClient(host='host', port=22, username='username', password='password')
  54. try:
  55. ret = client.execute('dmesg', sudo=True)
  56. print " ".join(ret["out"]), " E ".join(ret["err"]), ret["retval"]
  57. finally:
  58. client.close()
  59.  
  60. print stdout.read()
Add Comment
Please, Sign In to add comment