Advertisement
Guest User

Untitled

a guest
Aug 3rd, 2017
509
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.82 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. # Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com>
  4. #
  5. # This file is part of paramiko.
  6. #
  7. # Paramiko is free software; you can redistribute it and/or modify it under the
  8. # terms of the GNU Lesser General Public License as published by the Free
  9. # Software Foundation; either version 2.1 of the License, or (at your option)
  10. # any later version.
  11. #
  12. # Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY
  13. # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  14. # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  15. # details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public License
  18. # along with Paramiko; if not, write to the Free Software Foundation, Inc.,
  19. # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
  20.  
  21. """
  22. Sample script showing how to do local port forwarding over paramiko.
  23. This script connects to the requested SSH server and sets up local port
  24. forwarding (the openssh -L option) from a local port through a tunneled
  25. connection to a destination reachable from the SSH server machine.
  26. """
  27. import threading
  28. import getpass
  29. import os
  30. import socket
  31. import select
  32. try:
  33. import SocketServer
  34. except ImportError:
  35. import socketserver as SocketServer
  36.  
  37. import sys
  38. from optparse import OptionParser
  39.  
  40. import paramiko
  41.  
  42. SSH_PORT = 22
  43. DEFAULT_PORT = 4000
  44.  
  45. g_verbose = True
  46.  
  47.  
  48. class ForwardServer (SocketServer.ThreadingTCPServer):
  49. daemon_threads = True
  50. allow_reuse_address = True
  51.  
  52.  
  53. class Handler (SocketServer.BaseRequestHandler):
  54.  
  55. def handle(self):
  56. try:
  57. chan = self.ssh_transport.open_channel('direct-tcpip',
  58. (self.chain_host, self.chain_port),
  59. self.request.getpeername())
  60. except Exception as e:
  61. verbose('Incoming request to %s:%d failed: %s' % (self.chain_host,
  62. self.chain_port,
  63. repr(e)))
  64. return
  65. if chan is None:
  66. verbose('Incoming request to %s:%d was rejected by the SSH server.' %
  67. (self.chain_host, self.chain_port))
  68. return
  69.  
  70. verbose('Connected! Tunnel open %r -> %r -> %r' % (self.request.getpeername(),
  71. chan.getpeername(), (self.chain_host, self.chain_port)))
  72. while True:
  73. r, w, x = select.select([self.request, chan], [], [])
  74. if self.request in r:
  75. data = self.request.recv(1024)
  76. if len(data) == 0:
  77. break
  78. chan.send(data)
  79. if chan in r:
  80. data = chan.recv(1024)
  81. if len(data) == 0:
  82. break
  83. self.request.send(data)
  84.  
  85. peername = self.request.getpeername()
  86. chan.close()
  87. self.request.close()
  88. verbose('Tunnel closed from %r' % (peername,))
  89.  
  90.  
  91. def forward_tunnel(local_port, remote_host, remote_port, transport):
  92. # this is a little convoluted, but lets me configure things for the Handler
  93. # object. (SocketServer doesn't give Handlers any way to access the outer
  94. # server normally.)
  95. class SubHander (Handler):
  96. chain_host = remote_host
  97. chain_port = remote_port
  98. ssh_transport = transport
  99. t=threading.Thread(ForwardServer(('', local_port), SubHander).serve_forever(),daemon=True)
  100.  
  101. print("top cool")
  102. t.join()
  103.  
  104.  
  105.  
  106. def verbose(s):
  107. if g_verbose:
  108. print(s)
  109.  
  110.  
  111. HELP = """\
  112. Set up a forward tunnel across an SSH server, using paramiko. A local port
  113. (given with -p) is forwarded across an SSH session to an address:port from
  114. the SSH server. This is similar to the openssh -L option.
  115. """
  116.  
  117.  
  118. def get_host_port(spec, default_port):
  119. "parse 'hostname:22' into a host and port, with the port optional"
  120. args = (spec.split(':', 1) + [default_port])[:2]
  121. args[1] = int(args[1])
  122. return args[0], args[1]
  123.  
  124.  
  125. def parse_options():
  126. global g_verbose
  127.  
  128. parser = OptionParser(usage='usage: %prog [options] <ssh-server>[:<server-port>]',
  129. version='%prog 1.0', description=HELP)
  130. parser.add_option('-q', '--quiet', action='store_false', dest='verbose', default=True,
  131. help='squelch all informational output')
  132. parser.add_option('-p', '--local-port', action='store', type='int', dest='port',
  133. default=DEFAULT_PORT,
  134. help='local port to forward (default: %d)' % DEFAULT_PORT)
  135. parser.add_option('-u', '--user', action='store', type='string', dest='user',
  136. default=getpass.getuser(),
  137. help='username for SSH authentication (default: %s)' % getpass.getuser())
  138. parser.add_option('-K', '--key', action='store', type='string', dest='keyfile',
  139. default=None,
  140. help='private key file to use for SSH authentication')
  141. parser.add_option('', '--no-key', action='store_false', dest='look_for_keys', default=True,
  142. help='don\'t look for or use a private key file')
  143. parser.add_option('-P', '--password', action='store_true', dest='readpass', default=False,
  144. help='read password (for key or password auth) from stdin')
  145. parser.add_option('-r', '--remote', action='store', type='string', dest='remote', default=None, metavar='host:port',
  146. help='remote host and port to forward to')
  147. options, args = parser.parse_args()
  148.  
  149. if len(args) != 1:
  150. parser.error('Incorrect number of arguments.')
  151. if options.remote is None:
  152. parser.error('Remote address required (-r).')
  153.  
  154. g_verbose = options.verbose
  155. server_host, server_port = get_host_port(args[0], SSH_PORT)
  156. remote_host, remote_port = get_host_port(options.remote, SSH_PORT)
  157. return options, (server_host, server_port), (remote_host, remote_port)
  158.  
  159. class Threaded():
  160. options, server, remote = parse_options()
  161.  
  162. password = None
  163. if options.readpass:
  164. password = getpass.getpass('Enter SSH password: ')
  165.  
  166. client = paramiko.SSHClient()
  167. client.load_system_host_keys()
  168. client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  169.  
  170. verbose('Connecting to ssh host %s:%d ...' % (server[0], server[1]))
  171. try:
  172. client.connect(server[0], server[1], username=options.user, key_filename=options.keyfile,
  173. look_for_keys=options.look_for_keys, password=password)
  174. except Exception as e:
  175. print('*** Failed to connect to %s:%d: %r' % (server[0], server[1], e))
  176. sys.exit(1)
  177.  
  178. verbose('Now forwarding port %d to %s:%d ...' % (options.port, remote[0], remote[1]))
  179. target=forward_tunnel(options.port, remote[0], remote[1], client.get_transport())
  180.  
  181. def main():
  182.  
  183. if __name__ == '__main__':
  184. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement