ssh.py 997 B

12345678910111213141516171819202122232425262728293031323334353637
  1. """
  2. An SSH Tunneling tool
  3. @author: olivier.massot, 05-2020
  4. """
  5. from sshtunnel import SSHTunnelForwarder
  6. class SshTunnel:
  7. LOCAL_ADRESS = ('127.0.0.1', 6000)
  8. def __init__(self, host, remote_port, port=22, user="root", key_file="~/.ssh/id_rsa"):
  9. self.host = host
  10. self.remote_port = remote_port
  11. self.port = int(port)
  12. self.user = user
  13. self.key_file = key_file
  14. self._tunnel = SSHTunnelForwarder(
  15. (self.host, self.port),
  16. ssh_username=self.user,
  17. ssh_pkey=self.key_file,
  18. local_bind_address=self.LOCAL_ADRESS,
  19. remote_bind_address=('127.0.0.1', self.remote_port)
  20. )
  21. def start(self):
  22. """ Start the ssh tunnel
  23. """
  24. self._tunnel.start()
  25. if not self._tunnel.tunnel_is_up[self.LOCAL_ADRESS]:
  26. raise RuntimeError('Unable to open the SSH Tunnel')
  27. def stop(self):
  28. """ Stop the ssh tunnel
  29. """
  30. self._tunnel.stop()