1
#------------------------------------------------------------------------------
3
# This file is adapted from a paramiko demo, and thus licensed under LGPL 2.1.
4
# Original Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com>
5
# Edits Copyright (C) 2010 The IPython Team
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)
12
# Paramiko is distrubuted 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
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
# 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA.
20
#------------------------------------------------------------------------------
23
Sample script showing how to do local port forwarding over paramiko.
25
This script connects to the requested SSH server and sets up local port
26
forwarding (the openssh -L option) from a local port through a tunneled
27
connection to a destination reachable from the SSH server machine.
35
logger = logging.getLogger('ssh')
37
class ForwardServer (SocketServer.ThreadingTCPServer):
39
allow_reuse_address = True
42
class Handler (SocketServer.BaseRequestHandler):
46
chan = self.ssh_transport.open_channel('direct-tcpip',
47
(self.chain_host, self.chain_port),
48
self.request.getpeername())
49
except Exception as e:
50
logger.debug('Incoming request to %s:%d failed: %s' % (self.chain_host,
55
logger.debug('Incoming request to %s:%d was rejected by the SSH server.' %
56
(self.chain_host, self.chain_port))
59
logger.debug('Connected! Tunnel open %r -> %r -> %r' % (self.request.getpeername(),
60
chan.getpeername(), (self.chain_host, self.chain_port)))
62
r, w, x = select.select([self.request, chan], [], [])
64
data = self.request.recv(1024)
69
data = chan.recv(1024)
72
self.request.send(data)
75
logger.debug('Tunnel closed ')
78
def forward_tunnel(local_port, remote_host, remote_port, transport):
79
# this is a little convoluted, but lets me configure things for the Handler
80
# object. (SocketServer doesn't give Handlers any way to access the outer
82
class SubHander (Handler):
83
chain_host = remote_host
84
chain_port = remote_port
85
ssh_transport = transport
86
ForwardServer(('127.0.0.1', local_port), SubHander).serve_forever()
89
__all__ = ['forward_tunnel']