Debian Codegraph @

jupyter_client/ssh/forward.py

raw
1 """Sample script showing how to do local port forwarding over paramiko.
2
3 This script connects to the requested SSH server and sets up local port
4 forwarding (the openssh -L option) from a local port through a tunneled
5 connection to a destination reachable from the SSH server machine.
6 """
7
8 #
9 # This file is adapted from a paramiko demo, and thus licensed under LGPL 2.1.
10 # Original Copyright (C) 2003-2007 Robey Pointer <[email protected]>
11 # Edits Copyright (C) 2010 The IPython Team
12 #
13 # Paramiko is free software; you can redistribute it and/or modify it under the
14 # terms of the GNU Lesser General Public License as published by the Free
15 # Software Foundation; either version 2.1 of the License, or (at your option)
16 # any later version.
17 #
18 # Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY
19 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20 # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
21 # details.
22 #
23 # You should have received a copy of the GNU Lesser General Public License
24 # along with Paramiko; if not, write to the Free Software Foundation, Inc.,
25 # 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA.
26 import logging
27 import select
28 import socketserver
29 import typing as t
30
31 logger = logging.getLogger("ssh")
32
33
34 class ForwardServer(socketserver.ThreadingTCPServer):
35 """A server to use for ssh forwarding."""
36
37 daemon_threads = True
38 allow_reuse_address = True
39
40
41 class Handler(socketserver.BaseRequestHandler):
42 """A handle for server requests."""
43
44 @t.no_type_check
45 def handle(self):
46 """Handle a request."""
47 try:
48 chan = self.ssh_transport.open_channel(
49 "direct-tcpip",
50 (self.chain_host, self.chain_port),
51 self.request.getpeername(),
52 )
53 except Exception as e:
54 logger.debug(
55 "Incoming request to %s:%d failed: %s" % (self.chain_host, self.chain_port, repr(e))
56 )
57 return
58 if chan is None:
59 logger.debug(
60 "Incoming request to %s:%d was rejected by the SSH server."
61 % (self.chain_host, self.chain_port)
62 )
63 return
64
65 logger.debug(
66 f"Connected! Tunnel open {self.request.getpeername()!r} -> {chan.getpeername()!r} -> {(self.chain_host, self.chain_port)!r}"
67 )
68 while True:
69 r, _w, _x = select.select([self.request, chan], [], [])
70 if self.request in r:
71 data = self.request.recv(1024)
72 if len(data) == 0:
73 break
74 chan.send(data)
75 if chan in r:
76 data = chan.recv(1024)
77 if len(data) == 0:
78 break
79 self.request.send(data)
80 chan.close()
81 self.request.close()
82 logger.debug("Tunnel closed ")
83
84
85 def forward_tunnel(local_port: int, remote_host: str, remote_port: int, transport: t.Any) -> None:
86 """Forward an ssh tunnel."""
87
88 # this is a little convoluted, but lets me configure things for the Handler
89 # object. (SocketServer doesn't give Handlers any way to access the outer
90 # server normally.)
91 class SubHander(Handler):
92 chain_host = remote_host
93 chain_port = remote_port
94 ssh_transport = transport
95
96 ForwardServer(("127.0.0.1", local_port), SubHander).serve_forever()
97
98
99 __all__ = ["forward_tunnel"]