forked from pahaz/sshtunnel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sshtunnel.py
1928 lines (1627 loc) · 67.8 KB
/
sshtunnel.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
*sshtunnel* - Initiate SSH tunnels via a remote gateway.
``sshtunnel`` works by opening a port forwarding SSH connection in the
background, using threads.
The connection(s) are closed when explicitly calling the
:meth:`SSHTunnelForwarder.stop` method or using it as a context.
"""
import os
import sys
import socket
import getpass
import logging
import argparse
import warnings
import threading
from select import select
from binascii import hexlify
import paramiko
if sys.version_info[0] < 3: # pragma: no cover
import Queue as queue
import SocketServer as socketserver
string_types = basestring, # noqa
input_ = raw_input # noqa
else: # pragma: no cover
import queue
import socketserver
string_types = str
input_ = input
__version__ = '0.4.0'
__author__ = 'pahaz'
#: Timeout (seconds) for transport socket (``socket.settimeout``)
SSH_TIMEOUT = 0.1 # ``None`` may cause a block of transport thread
#: Timeout (seconds) for tunnel connection (open_channel timeout)
TUNNEL_TIMEOUT = 10.0
_DAEMON = True #: Use daemon threads in connections
_CONNECTION_COUNTER = 1
_LOCK = threading.Lock()
_DEPRECATIONS = {
'ssh_address': 'ssh_address_or_host',
'ssh_host': 'ssh_address_or_host',
'ssh_private_key': 'ssh_pkey',
'raise_exception_if_any_forwarder_have_a_problem': 'mute_exceptions'
}
# logging
DEFAULT_LOGLEVEL = logging.ERROR #: default level if no logger passed (ERROR)
TRACE_LEVEL = 1
logging.addLevelName(TRACE_LEVEL, 'TRACE')
DEFAULT_SSH_DIRECTORY = '~/.ssh'
_StreamServer = socketserver.UnixStreamServer if os.name == 'posix' \
else socketserver.TCPServer
#: Path of optional ssh configuration file
DEFAULT_SSH_DIRECTORY = '~/.ssh'
SSH_CONFIG_FILE = os.path.join(DEFAULT_SSH_DIRECTORY, 'config')
########################
# #
# Utils #
# #
########################
def check_host(host):
assert isinstance(host, string_types), 'IP is not a string ({0})'.format(
type(host).__name__
)
def check_port(port):
assert isinstance(port, int), 'PORT is not a number'
assert port >= 0, 'PORT < 0 ({0})'.format(port)
def check_address(address):
"""
Check if the format of the address is correct
Arguments:
address (tuple):
(``str``, ``int``) representing an IP address and port,
respectively
.. note::
alternatively a local ``address`` can be a ``str`` when working
with UNIX domain sockets, if supported by the platform
Raises:
ValueError:
raised when address has an incorrect format
Example:
>>> check_address(('127.0.0.1', 22))
"""
if isinstance(address, tuple):
check_host(address[0])
check_port(address[1])
elif isinstance(address, string_types):
if os.name != 'posix':
raise ValueError('Platform does not support UNIX domain sockets')
if not (os.path.exists(address) or
os.access(os.path.dirname(address), os.W_OK)):
raise ValueError('ADDRESS not a valid socket domain socket ({0})'
.format(address))
else:
raise ValueError('ADDRESS is not a tuple, string, or character buffer '
'({0})'.format(type(address).__name__))
def check_addresses(address_list, is_remote=False):
"""
Check if the format of the addresses is correct
Arguments:
address_list (list[tuple]):
Sequence of (``str``, ``int``) pairs, each representing an IP
address and port respectively
.. note::
when supported by the platform, one or more of the elements in
the list can be of type ``str``, representing a valid UNIX
domain socket
is_remote (boolean):
Whether or not the address list
Raises:
AssertionError:
raised when ``address_list`` contains an invalid element
ValueError:
raised when any address in the list has an incorrect format
Example:
>>> check_addresses([('127.0.0.1', 22), ('127.0.0.1', 2222)])
"""
assert all(isinstance(x, (tuple, string_types)) for x in address_list)
if (is_remote and any(isinstance(x, string_types) for x in address_list)):
raise AssertionError('UNIX domain sockets not allowed for remote'
'addresses')
for address in address_list:
check_address(address)
def create_logger(logger=None,
loglevel=None,
capture_warnings=True,
add_paramiko_handler=True):
"""
Attach or create a new logger and add a console handler if not present
Arguments:
logger (Optional[logging.Logger]):
:class:`logging.Logger` instance; a new one is created if this
argument is empty
loglevel (Optional[str or int]):
:class:`logging.Logger`'s level, either as a string (i.e.
``ERROR``) or in numeric format (10 == ``DEBUG``)
.. note:: a value of 1 == ``TRACE`` enables Tracing mode
capture_warnings (boolean):
Enable/disable capturing the events logged by the warnings module
into ``logger``'s handlers
Default: True
.. note:: ignored in python 2.6
add_paramiko_handler (boolean):
Whether or not add a console handler for ``paramiko.transport``'s
logger if no handler present
Default: True
Return:
:class:`logging.Logger`
"""
logger = logger or logging.getLogger(
'sshtunnel.SSHTunnelForwarder'
)
if not any(isinstance(x, logging.Handler) for x in logger.handlers):
logger.setLevel(loglevel or DEFAULT_LOGLEVEL)
console_handler = logging.StreamHandler()
_add_handler(logger,
handler=console_handler,
loglevel=loglevel or DEFAULT_LOGLEVEL)
if loglevel: # override if loglevel was set
logger.setLevel(loglevel)
for handler in logger.handlers:
handler.setLevel(loglevel)
if add_paramiko_handler:
_check_paramiko_handlers(logger=logger)
if capture_warnings and sys.version_info >= (2, 7):
logging.captureWarnings(True)
pywarnings = logging.getLogger('py.warnings')
pywarnings.handlers.extend(logger.handlers)
return logger
def _add_handler(logger, handler=None, loglevel=None):
"""
Add a handler to an existing logging.Logger object
"""
handler.setLevel(loglevel or DEFAULT_LOGLEVEL)
if handler.level <= logging.DEBUG:
_fmt = '%(asctime)s| %(levelname)-4.3s|%(threadName)10.9s/' \
'%(lineno)04d@%(module)-10.9s| %(message)s'
handler.setFormatter(logging.Formatter(_fmt))
else:
handler.setFormatter(logging.Formatter(
'%(asctime)s| %(levelname)-8s| %(message)s'
))
logger.addHandler(handler)
def _check_paramiko_handlers(logger=None):
"""
Add a console handler for paramiko.transport's logger if not present
"""
paramiko_logger = logging.getLogger('paramiko.transport')
if not paramiko_logger.handlers:
if logger:
paramiko_logger.handlers = logger.handlers
else:
console_handler = logging.StreamHandler()
console_handler.setFormatter(
logging.Formatter('%(asctime)s | %(levelname)-8s| PARAMIKO: '
'%(lineno)03d@%(module)-10s| %(message)s')
)
paramiko_logger.addHandler(console_handler)
def address_to_str(address):
if isinstance(address, tuple):
return '{0[0]}:{0[1]}'.format(address)
return str(address)
def get_connection_id():
global _CONNECTION_COUNTER
with _LOCK:
uid = _CONNECTION_COUNTER
_CONNECTION_COUNTER += 1
return uid
def _remove_none_values(dictionary):
""" Remove dictionary keys whose value is None """
return list(map(dictionary.pop,
[i for i in dictionary if dictionary[i] is None]))
########################
# #
# Errors #
# #
########################
class BaseSSHTunnelForwarderError(Exception):
""" Exception raised by :class:`SSHTunnelForwarder` errors """
def __init__(self, *args, **kwargs):
self.value = kwargs.pop('value', args[0] if args else '')
def __str__(self):
return self.value
class HandlerSSHTunnelForwarderError(BaseSSHTunnelForwarderError):
""" Exception for Tunnel forwarder errors """
pass
########################
# #
# Handlers #
# #
########################
class _ForwardHandler(socketserver.BaseRequestHandler):
""" Base handler for tunnel connections """
remote_address = None
ssh_transport = None
logger = None
info = None
def _redirect(self, chan):
while chan.active:
rqst, _, _ = select([self.request, chan], [], [], 5)
if self.request in rqst:
data = self.request.recv(16384)
if not data:
self.logger.log(
TRACE_LEVEL,
'>>> OUT {0} recv empty data >>>'.format(self.info)
)
break
if self.logger.isEnabledFor(TRACE_LEVEL):
self.logger.log(
TRACE_LEVEL,
'>>> OUT {0} send to {1}: {2} >>>'.format(
self.info,
self.remote_address,
hexlify(data)
)
)
chan.sendall(data)
if chan in rqst: # else
if not chan.recv_ready():
self.logger.log(
TRACE_LEVEL,
'<<< IN {0} recv is not ready <<<'.format(self.info)
)
break
data = chan.recv(16384)
if self.logger.isEnabledFor(TRACE_LEVEL):
self.logger.log(
TRACE_LEVEL,
'<<< IN {0} recv: {1} <<<'.format(self.info, hexlify(data))
)
self.request.sendall(data)
def handle(self):
uid = get_connection_id()
self.info = '#{0} <-- {1}'.format(uid, self.client_address or
self.server.local_address)
src_address = self.request.getpeername()
if not isinstance(src_address, tuple):
src_address = ('dummy', 12345)
try:
chan = self.ssh_transport.open_channel(
kind='direct-tcpip',
dest_addr=self.remote_address,
src_addr=src_address,
timeout=TUNNEL_TIMEOUT
)
except Exception as e: # pragma: no cover
msg_tupe = 'ssh ' if isinstance(e, paramiko.SSHException) else ''
exc_msg = 'open new channel {0}error: {1}'.format(msg_tupe, e)
log_msg = '{0} {1}'.format(self.info, exc_msg)
self.logger.log(TRACE_LEVEL, log_msg)
raise HandlerSSHTunnelForwarderError(exc_msg)
self.logger.log(TRACE_LEVEL, '{0} connected'.format(self.info))
try:
self._redirect(chan)
except socket.error:
# Sometimes a RST is sent and a socket error is raised, treat this
# exception. It was seen that a 3way FIN is processed later on, so
# no need to make an ordered close of the connection here or raise
# the exception beyond this point...
self.logger.log(TRACE_LEVEL, '{0} sending RST'.format(self.info))
except Exception as e:
self.logger.log(TRACE_LEVEL,
'{0} error: {1}'.format(self.info, repr(e)))
finally:
chan.close()
self.request.close()
self.logger.log(TRACE_LEVEL,
'{0} connection closed.'.format(self.info))
class _ForwardServer(socketserver.TCPServer): # Not Threading
"""
Non-threading version of the forward server
"""
allow_reuse_address = True # faster rebinding
def __init__(self, *args, **kwargs):
self.logger = create_logger(kwargs.pop('logger', None))
self.tunnel_ok = queue.Queue(1)
socketserver.TCPServer.__init__(self, *args, **kwargs)
def handle_error(self, request, client_address):
(exc_class, exc, tb) = sys.exc_info()
local_side = request.getsockname()
remote_side = self.remote_address
self.logger.error('Could not establish connection from local {0} '
'to remote {1} side of the tunnel: {2}'
.format(local_side, remote_side, exc))
try:
self.tunnel_ok.put(False, block=False, timeout=0.1)
except queue.Full:
# wait untill tunnel_ok.get is called
pass
except exc:
self.logger.error('unexpected internal error: {0}'.format(exc))
@property
def local_address(self):
return self.server_address
@property
def local_host(self):
return self.server_address[0]
@property
def local_port(self):
return self.server_address[1]
@property
def remote_address(self):
return self.RequestHandlerClass.remote_address
@property
def remote_host(self):
return self.RequestHandlerClass.remote_address[0]
@property
def remote_port(self):
return self.RequestHandlerClass.remote_address[1]
class _ThreadingForwardServer(socketserver.ThreadingMixIn, _ForwardServer):
"""
Allow concurrent connections to each tunnel
"""
# If True, cleanly stop threads created by ThreadingMixIn when quitting
# This value is overrides by SSHTunnelForwarder.daemon_forward_servers
daemon_threads = _DAEMON
class _StreamForwardServer(_StreamServer):
"""
Serve over domain sockets (does not work on Windows)
"""
def __init__(self, *args, **kwargs):
self.logger = create_logger(kwargs.pop('logger', None))
self.tunnel_ok = queue.Queue(1)
_StreamServer.__init__(self, *args, **kwargs)
@property
def local_address(self):
return self.server_address
@property
def local_host(self):
return None
@property
def local_port(self):
return None
@property
def remote_address(self):
return self.RequestHandlerClass.remote_address
@property
def remote_host(self):
return self.RequestHandlerClass.remote_address[0]
@property
def remote_port(self):
return self.RequestHandlerClass.remote_address[1]
class _ThreadingStreamForwardServer(socketserver.ThreadingMixIn,
_StreamForwardServer):
"""
Allow concurrent connections to each tunnel
"""
# If True, cleanly stop threads created by ThreadingMixIn when quitting
# This value is overrides by SSHTunnelForwarder.daemon_forward_servers
daemon_threads = _DAEMON
class SSHTunnelForwarder(object):
"""
**SSH tunnel class**
- Initialize a SSH tunnel to a remote host according to the input
arguments
- Optionally:
+ Read an SSH configuration file (typically ``~/.ssh/config``)
+ Load keys from a running SSH agent (i.e. Pageant, GNOME Keyring)
Raises:
:class:`.BaseSSHTunnelForwarderError`:
raised by SSHTunnelForwarder class methods
:class:`.HandlerSSHTunnelForwarderError`:
raised by tunnel forwarder threads
.. note::
Attributes ``mute_exceptions`` and
``raise_exception_if_any_forwarder_have_a_problem``
(deprecated) may be used to silence most exceptions raised
from this class
Keyword Arguments:
ssh_address_or_host (tuple or str):
IP or hostname of ``REMOTE GATEWAY``. It may be a two-element
tuple (``str``, ``int``) representing IP and port respectively,
or a ``str`` representing the IP address only
.. versionadded:: 0.0.4
ssh_config_file (str):
SSH configuration file that will be read. If explicitly set to
``None``, parsing of this configuration is omitted
Default: :const:`SSH_CONFIG_FILE`
.. versionadded:: 0.0.4
ssh_host_key (str):
Representation of a line in an OpenSSH-style "known hosts"
file.
``REMOTE GATEWAY``'s key fingerprint will be compared to this
host key in order to prevent against SSH server spoofing.
Important when using passwords in order not to accidentally
do a login attempt to a wrong (perhaps an attacker's) machine
ssh_username (str):
Username to authenticate as in ``REMOTE SERVER``
Default: current local user name
ssh_password (str):
Text representing the password used to connect to ``REMOTE
SERVER`` or for unlocking a private key.
.. note::
Avoid coding secret password directly in the code, since this
may be visible and make your service vulnerable to attacks
ssh_port (int):
Optional port number of the SSH service on ``REMOTE GATEWAY``,
when `ssh_address_or_host`` is a ``str`` representing the
IP part of ``REMOTE GATEWAY``'s address
Default: 22
ssh_pkey (str or paramiko.PKey):
**Private** key file name (``str``) to obtain the public key
from or a **public** key (:class:`paramiko.pkey.PKey`)
ssh_private_key_password (str):
Password for an encrypted ``ssh_pkey``
.. note::
Avoid coding secret password directly in the code, since this
may be visible and make your service vulnerable to attacks
ssh_proxy (socket-like object or tuple):
Proxy where all SSH traffic will be passed through.
It might be for example a :class:`paramiko.proxy.ProxyCommand`
instance.
See either the :class:`paramiko.transport.Transport`'s sock
parameter documentation or ``ProxyCommand`` in ``ssh_config(5)``
for more information.
It is also possible to specify the proxy address as a tuple of
type (``str``, ``int``) representing proxy's IP and port
.. note::
Ignored if ``ssh_proxy_enabled`` is False
.. versionadded:: 0.0.5
ssh_proxy_enabled (boolean):
Enable/disable SSH proxy. If True and user's
``ssh_config_file`` contains a ``ProxyCommand`` directive
that matches the specified ``ssh_address_or_host``,
a :class:`paramiko.proxy.ProxyCommand` object will be created where
all SSH traffic will be passed through
Default: ``True``
.. versionadded:: 0.0.4
local_bind_address (tuple):
Local tuple in the format (``str``, ``int``) representing the
IP and port of the local side of the tunnel. Both elements in
the tuple are optional so both ``('', 8000)`` and
``('10.0.0.1', )`` are valid values
Default: ``('0.0.0.0', RANDOM_PORT)``
.. versionchanged:: 0.0.8
Added the ability to use a UNIX domain socket as local bind
address
local_bind_addresses (list[tuple]):
In case more than one tunnel is established at once, a list
of tuples (in the same format as ``local_bind_address``)
can be specified, such as [(ip1, port_1), (ip_2, port2), ...]
Default: ``[local_bind_address]``
.. versionadded:: 0.0.4
remote_bind_address (tuple):
Remote tuple in the format (``str``, ``int``) representing the
IP and port of the remote side of the tunnel.
remote_bind_addresses (list[tuple]):
In case more than one tunnel is established at once, a list
of tuples (in the same format as ``remote_bind_address``)
can be specified, such as [(ip1, port_1), (ip_2, port2), ...]
Default: ``[remote_bind_address]``
.. versionadded:: 0.0.4
allow_agent (boolean):
Enable/disable load of keys from an SSH agent
Default: ``True``
.. versionadded:: 0.0.8
host_pkey_directories (list):
Look for pkeys in folders on this list, for example ['~/.ssh'].
Default: ``None`` (disabled)
.. versionadded:: 0.1.4
compression (boolean):
Turn on/off transport compression. By default compression is
disabled since it may negatively affect interactive sessions
Default: ``False``
.. versionadded:: 0.0.8
logger (logging.Logger):
logging instance for sshtunnel and paramiko
Default: :class:`logging.Logger` instance with a single
:class:`logging.StreamHandler` handler and
:const:`DEFAULT_LOGLEVEL` level
.. versionadded:: 0.0.3
mute_exceptions (boolean):
Allow silencing :class:`BaseSSHTunnelForwarderError` or
:class:`HandlerSSHTunnelForwarderError` exceptions when enabled
Default: ``False``
.. versionadded:: 0.0.8
set_keepalive (float):
Interval in seconds defining the period in which, if no data
was sent over the connection, a *'keepalive'* packet will be
sent (and ignored by the remote host). This can be useful to
keep connections alive over a NAT. You can set to 0.0 for
disable keepalive.
Default: 5.0 (no keepalive packets are sent)
.. versionadded:: 0.0.7
threaded (boolean):
Allow concurrent connections over a single tunnel
Default: ``True``
.. versionadded:: 0.0.3
ssh_address (str):
Superseded by ``ssh_address_or_host``, tuple of type (str, int)
representing the IP and port of ``REMOTE SERVER``
.. deprecated:: 0.0.4
ssh_host (str):
Superseded by ``ssh_address_or_host``, tuple of type
(str, int) representing the IP and port of ``REMOTE SERVER``
.. deprecated:: 0.0.4
ssh_private_key (str or paramiko.PKey):
Superseded by ``ssh_pkey``, which can represent either a
**private** key file name (``str``) or a **public** key
(:class:`paramiko.pkey.PKey`)
.. deprecated:: 0.0.8
raise_exception_if_any_forwarder_have_a_problem (boolean):
Allow silencing :class:`BaseSSHTunnelForwarderError` or
:class:`HandlerSSHTunnelForwarderError` exceptions when set to
False
Default: ``True``
.. versionadded:: 0.0.4
.. deprecated:: 0.0.8 (use ``mute_exceptions`` instead)
Attributes:
tunnel_is_up (dict):
Describe whether or not the other side of the tunnel was reported
to be up (and we must close it) or not (skip shutting down that
tunnel)
.. note::
This attribute should not be modified
.. note::
When :attr:`.skip_tunnel_checkup` is disabled or the local bind
is a UNIX socket, the value will always be ``True``
**Example**::
{('127.0.0.1', 55550): True, # this tunnel is up
('127.0.0.1', 55551): False} # this one isn't
where 55550 and 55551 are the local bind ports
skip_tunnel_checkup (boolean):
Disable tunnel checkup (default for backwards compatibility).
.. versionadded:: 0.1.0
"""
skip_tunnel_checkup = True
# This option affects the `ForwardServer` and all his threads
daemon_forward_servers = _DAEMON #: flag tunnel threads in daemon mode
# This option affect only `Transport` thread
daemon_transport = _DAEMON #: flag SSH transport thread in daemon mode
def local_is_up(self, target):
"""
Check if a tunnel is up (remote target's host is reachable on TCP
target's port)
Arguments:
target (tuple):
tuple of type (``str``, ``int``) indicating the listen IP
address and port
Return:
boolean
.. deprecated:: 0.1.0
Replaced by :meth:`.check_tunnels()` and :attr:`.tunnel_is_up`
"""
try:
check_address(target)
except ValueError:
self.logger.warning('Target must be a tuple (IP, port), where IP '
'is a string (i.e. "192.168.0.1") and port is '
'an integer (i.e. 40000). Alternatively '
'target can be a valid UNIX domain socket.')
return False
self.check_tunnels()
return self.tunnel_is_up.get(target, True)
def check_tunnels(self):
"""
Check that if all tunnels are established and populates
:attr:`.tunnel_is_up`
"""
skip_tunnel_checkup = self.skip_tunnel_checkup
try:
# force tunnel check at this point
self.skip_tunnel_checkup = False
for _srv in self._server_list:
self._check_tunnel(_srv)
finally:
self.skip_tunnel_checkup = skip_tunnel_checkup # roll it back
def _check_tunnel(self, _srv):
""" Check if tunnel is already established """
if self.skip_tunnel_checkup:
self.tunnel_is_up[_srv.local_address] = True
return
self.logger.info('Checking tunnel to: {0}'.format(_srv.remote_address))
if isinstance(_srv.local_address, string_types): # UNIX stream
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(TUNNEL_TIMEOUT)
try:
# Windows raises WinError 10049 if trying to connect to 0.0.0.0
connect_to = ('127.0.0.1', _srv.local_port) \
if _srv.local_host == '0.0.0.0' else _srv.local_address
s.connect(connect_to)
self.tunnel_is_up[_srv.local_address] = _srv.tunnel_ok.get(
timeout=TUNNEL_TIMEOUT * 1.1
)
self.logger.debug(
'Tunnel to {0} is DOWN'.format(_srv.remote_address)
)
except socket.error:
self.logger.debug(
'Tunnel to {0} is DOWN'.format(_srv.remote_address)
)
self.tunnel_is_up[_srv.local_address] = False
except queue.Empty:
self.logger.debug(
'Tunnel to {0} is UP'.format(_srv.remote_address)
)
self.tunnel_is_up[_srv.local_address] = True
finally:
s.close()
def _make_ssh_forward_handler_class(self, remote_address_):
"""
Make SSH Handler class
"""
class Handler(_ForwardHandler):
remote_address = remote_address_
ssh_transport = self._transport
logger = self.logger
return Handler
def _make_ssh_forward_server_class(self, remote_address_):
return _ThreadingForwardServer if self._threaded else _ForwardServer
def _make_stream_ssh_forward_server_class(self, remote_address_):
return _ThreadingStreamForwardServer if self._threaded \
else _StreamForwardServer
def _make_ssh_forward_server(self, remote_address, local_bind_address):
"""
Make SSH forward proxy Server class
"""
_Handler = self._make_ssh_forward_handler_class(remote_address)
try:
forward_maker_class = self._make_stream_ssh_forward_server_class \
if isinstance(local_bind_address, string_types) \
else self._make_ssh_forward_server_class
_Server = forward_maker_class(remote_address)
ssh_forward_server = _Server(
local_bind_address,
_Handler,
logger=self.logger,
)
if ssh_forward_server:
ssh_forward_server.daemon_threads = self.daemon_forward_servers
self._server_list.append(ssh_forward_server)
self.tunnel_is_up[ssh_forward_server.server_address] = False
else:
self._raise(
BaseSSHTunnelForwarderError,
'Problem setting up ssh {0} <> {1} forwarder. You can '
'suppress this exception by using the `mute_exceptions`'
'argument'.format(address_to_str(local_bind_address),
address_to_str(remote_address))
)
except IOError:
self._raise(
BaseSSHTunnelForwarderError,
"Couldn't open tunnel {0} <> {1} might be in use or "
"destination not reachable".format(
address_to_str(local_bind_address),
address_to_str(remote_address)
)
)
def __init__(
self,
ssh_address_or_host=None,
ssh_config_file=SSH_CONFIG_FILE,
ssh_host_key=None,
ssh_password=None,
ssh_pkey=None,
ssh_private_key_password=None,
ssh_proxy=None,
ssh_proxy_enabled=True,
ssh_username=None,
local_bind_address=None,
local_bind_addresses=None,
logger=None,
mute_exceptions=False,
remote_bind_address=None,
remote_bind_addresses=None,
set_keepalive=5.0,
threaded=True, # old version False
compression=None,
allow_agent=True, # look for keys from an SSH agent
host_pkey_directories=None, # look for keys in ~/.ssh
*args,
**kwargs # for backwards compatibility
):
self.logger = logger or create_logger()
# Ensure paramiko.transport has a console handler
_check_paramiko_handlers(logger=logger)
self.ssh_host_key = ssh_host_key
self.set_keepalive = set_keepalive
self._server_list = [] # reset server list
self.tunnel_is_up = {} # handle tunnel status
self._threaded = threaded
self.is_alive = False
# Check if deprecated arguments ssh_address or ssh_host were used
for deprecated_argument in ['ssh_address', 'ssh_host']:
ssh_address_or_host = self._process_deprecated(ssh_address_or_host,
deprecated_argument,
kwargs)
# other deprecated arguments
ssh_pkey = self._process_deprecated(ssh_pkey,
'ssh_private_key',
kwargs)
self._raise_fwd_exc = self._process_deprecated(
None,
'raise_exception_if_any_forwarder_have_a_problem',
kwargs) or not mute_exceptions
if isinstance(ssh_address_or_host, tuple):
check_address(ssh_address_or_host)
(ssh_host, ssh_port) = ssh_address_or_host
else:
ssh_host = ssh_address_or_host
ssh_port = kwargs.pop('ssh_port', None)
if kwargs:
raise ValueError('Unknown arguments: {0}'.format(kwargs))
# remote binds
self._remote_binds = self._get_binds(remote_bind_address,
remote_bind_addresses,
is_remote=True)
# local binds
self._local_binds = self._get_binds(local_bind_address,
local_bind_addresses)
self._local_binds = self._consolidate_binds(self._local_binds,
self._remote_binds)
(self.ssh_host,
self.ssh_username,
ssh_pkey, # still needs to go through _consolidate_auth
self.ssh_port,
self.ssh_proxy,
self.compression) = self._read_ssh_config(
ssh_host,
ssh_config_file,
ssh_username,
ssh_pkey,
ssh_port,
ssh_proxy if ssh_proxy_enabled else None,
compression,
self.logger
)
(self.ssh_password, self.ssh_pkeys) = self._consolidate_auth(
ssh_password=ssh_password,
ssh_pkey=ssh_pkey,
ssh_pkey_password=ssh_private_key_password,
allow_agent=allow_agent,
host_pkey_directories=host_pkey_directories,
logger=self.logger
)
check_host(self.ssh_host)
check_port(self.ssh_port)
self.logger.info("Connecting to gateway: {0}:{1} as user '{2}'"
.format(self.ssh_host,
self.ssh_port,
self.ssh_username))
self.logger.debug('Concurrent connections allowed: {0}'
.format(self._threaded))
@staticmethod
def _read_ssh_config(ssh_host,
ssh_config_file,
ssh_username=None,
ssh_pkey=None,
ssh_port=None,
ssh_proxy=None,
compression=None,
logger=None):
"""
Read ssh_config_file and tries to look for user (ssh_username),
identityfile (ssh_pkey), port (ssh_port) and proxycommand
(ssh_proxy) entries for ssh_host