Guest User

Untitled

a guest
Aug 23rd, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.73 KB | None | 0 0
  1. def create_ssh_tunnel(self, tunnel_password):
  2. """
  3. This method is used to create ssh tunnel and update the IP Address and
  4. IP Address and port to localhost and the local bind port return by the
  5. SSHTunnelForwarder class.
  6. :return: True if tunnel is successfully created else error message.
  7. """
  8. # Fetch Logged in User Details.
  9. user = User.query.filter_by(id=current_user.id).first()
  10. if user is None:
  11. return False, gettext("Unauthorized request.")
  12.  
  13. try:
  14. tunnel_password = decrypt(tunnel_password, user.password)
  15. # Handling of non ascii password (Python2)
  16. if hasattr(str, 'decode'):
  17. tunnel_password =
  18. tunnel_password.decode('utf-8').encode('utf-8')
  19. # password is in bytes, for python3 we need it in string
  20. elif isinstance(tunnel_password, bytes):
  21. tunnel_password = tunnel_password.decode()
  22.  
  23. except Exception as e:
  24. current_app.logger.exception(e)
  25. return False, "Failed to decrypt the SSH tunnel "
  26. "password.nError: {0}".format(str(e))
  27.  
  28. try:
  29. # If authentication method is 1 then it uses identity file
  30. # and password
  31. if self.tunnel_authentication == 1:
  32. self.tunnel_object = SSHTunnelForwarder(
  33. self.tunnel_host,
  34. ssh_username=self.tunnel_username,
  35. ssh_pkey=get_complete_file_path(self.tunnel_identity_file),
  36. ssh_private_key_password=tunnel_password,
  37. remote_bind_address=(self.host, self.port)
  38. )
  39. else:
  40. self.tunnel_object = SSHTunnelForwarder(
  41. self.tunnel_host,
  42. ssh_username=self.tunnel_username,
  43. ssh_password=tunnel_password,
  44. remote_bind_address=(self.host, self.port)
  45. )
  46.  
  47. self.tunnel_object.start()
  48. except BaseSSHTunnelForwarderError as e:
  49. current_app.logger.exception(e)
  50. return False, "Failed to create the SSH tunnel."
  51. "nError: {0}".format(str(e))
  52.  
  53. # Update the port to communicate locally
  54. self.local_bind_port = self.tunnel_object.local_bind_port
  55.  
  56. return True, None
  57.  
  58. if self.tunnel_authentication == 1:
  59. self.tunnel_object = SSHTunnelForwarder(
  60. (self.tunnel_host, int(self.tunnel_port)),
  61. ssh_username=self.tunnel_username,
  62. ssh_pkey=get_complete_file_path(self.tunnel_identity_file),
  63. ssh_private_key_password=tunnel_password,
  64. remote_bind_address=(self.host, self.port)
  65. )
  66. else:
  67. self.tunnel_object = SSHTunnelForwarder(
  68. (self.tunnel_host, int(self.tunnel_port)),
  69. ssh_username=self.tunnel_username,
  70. ssh_password=tunnel_password,
  71. remote_bind_address=(self.host, self.port)
  72. )
Add Comment
Please, Sign In to add comment