
    Mh-4                        d Z ddlZddlZddlZddlZddlZddlZddlZddlmZm	Z	 ddl
mZ 	  ej                    5   ej        de           ddlZej        j        Zddd           n# 1 swxY w Y   ddlmZ n# e$ r dZ G d d	e          ZY nw xY w	 ddlZn# e$ r dZY nw xY w G d
 de          Zd Z ej        dej                  ZddZd Zd Z	 ddZddZ 	 ddZ!d Z"d Z#	 ddZ$ddZ%ej&        dk    re$Z'ne!Z'g dZ(dS ) zXBasic ssh tunnel utilities, and convenience functions for tunneling
zeromq connections.
    N)getpassgetuser)Processignore   )forward_tunnelc                       e Zd ZdS )SSHExceptionN__name__
__module____qualname__     N/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/zmq/ssh/tunnel.pyr
   r
      s        r   r
   c                       e Zd ZdS )MaxRetryExceededNr   r   r   r   r   r   )   s        Dr   r   c                 8   g }g }t          |           D ]l}t          j                    }|                    d           |                    |                                d                    |                    |           m|D ]}|                                 |S )z4Select and return n random ports that are available.) r   r   )rangesocketbindappendgetsocknameclose)nportssocketsisocks        r   select_random_portsr!   -   s    EG1XX  }		'T%%''*+++t  

Lr   s   pass(word|phrase)c                 `    |t           j        dk    }|st          }nt          } || |          S )zAttempt to make an ssh connection without a password.
    This is mainly used for requiring password input only once
    when many tunnels may be connected to the same server.

    If paramiko is None, the default for the platform is chosen.
    Nwin32)sysplatform_try_passwordless_openssh_try_passwordless_paramiko)serverkeyfileparamikofs       r   try_passwordless_sshr,   A   s<     <7* '%&1VWr   c                    t           t          d          d| z   }|r|d|z   z  }|dz  }t          j                                        }|                    dd           d}t          j        ||          }d	}t          |          D ]`}	 |                    |t          gd
          }|dk    rt          d          	  dS # t           j        $ r Y Kt           j        $ r Y  dS w xY wt          d| d          )z.Try passwordless login with shell ssh command.Nz!pexpect unavailable, use paramikozssh -f z -i z exitSSH_ASKPASS,Are you sure you want to continue connectingenv
   皙?timeoutr   2The authenticity of the host can't be established.FTFailed after 	 attempts)pexpectImportErrorosenvironcopypopspawnr   expect_password_patr
   TIMEOUTEOFr   )	r(   r)   cmdr1   
ssh_newkeyp	MAX_RETRY_r   s	            r   r&   r&   Q   sD   =>>>
f
C  v7NC *//

CGGM4   ?Jcs###AI9  	*m4cBBAAvv"I    55  	 	 	H{ 	 	 	444	
 ?9???
@
@@s   3CC&C&%C&c                 |   t           ,d}t          j        dk    r|dz  }n|dz  }t          |          t	          |           \  }} }t          j                    }t          j                            d          }	 |	                    |           n# t          $ r Y nw xY wt          j                            dd          }|r5t          t           | d          }|                     |                       	 |                    | |||d	
           |                                 d	S # t           j        $ r Y dS w xY w)z%Try passwordless login with paramiko.NzParamiko unavailable, r#   z=Paramiko is required for ssh tunneled connections on Windows.zuse OpenSSH.z~/.ssh/known_hostsPYZMQ_PARAMIKO_HOST_KEY_POLICYPolicyT)usernamekey_filenamelook_for_keysF)r*   r$   r%   r:   _split_server	SSHClientr;   path
expanduserload_host_keysFileNotFoundErrorr<   getgetattrset_missing_host_key_policyconnectr   AuthenticationException)	r(   r)   msgrL   portclientknown_hostspolicy_namepolicys	            r   r'   r'   t   sl   &<7""RRCC>!C#*622Hfd!!F'$$%9::Kk****    *..!A4HHK 5k#9#9#9::**6688444D8'QU 	 	
 	
 	
 	t	 +   uus$   :B 
BB8D( (D;:D;<   c                 V    t          ||||||          \  }} | j        |           |S )aT  Connect a socket to an address via an ssh tunnel.

    This is a wrapper for socket.connect(addr), when addr is not accessible
    from the local machine.  It simply creates an ssh tunnel using the remaining args,
    and calls socket.connect('tcp://localhost:lport') where lport is the randomly
    selected local port of the tunnel.

    )r)   passwordr*   r5   )open_tunnelrX   )	r   addrr(   r)   rb   r*   r5   new_urltunnels	            r   tunnel_connectionrg      sG     "  OGV FN7Mr   c           	      "   t          d          d         }|                     d          \  }} |                     d          \  }}	t          |	          }	|t          j        dk    }|rt
          }
nt          }
 |
||	|||||          }d| |fS )	zOpen a tunneled connection from a 0MQ url.

    For use inside tunnel_connection.

    Returns
    -------

    (url, tunnel) : (str, object)
        The 0MQ url that has been forwarded, and the tunnel object
    r   r   z://:Nr#   )remoteipr)   rb   r5   ztcp://127.0.0.1:)r!   splitintr$   r%   paramiko_tunnelopenssh_tunnel)rd   r(   r)   rb   r*   r5   lport	transportiprporttunnelfrf   s               r   rc   rc      s      ""1%Ejj''OIt

3IBJJE<7* !! W  F &e%%v--r   	127.0.0.1c                    t           t          d          d}|r|d|z   z  }d|v r |                    d          \  }}|d| z  }| d| }	t          j        |	d	          \  }
}|st	          |
|
                    d
          dz   |
                    d                             }| d|  d| d| d| 	}	t          j        |	d	          \  }
}|s1t          j        t          |		                    ddd                     |S | d|  d| d| d| d| }	t          j                                        }|                    dd           d}t          j        |	|          }d}d}t          |          D ]}	 |                    |t"          gd          }|dk    rt%          d          	 |rt'          d           d}|t)          | d          }|                    |           d}v# t           j        $ r Y t           j        $ rb |j        rOt'          |j                   t'          |j                   t'          |j                   t7          d|	 d           |j        cY c S w xY wt;          d!| d"          )#a  Create an ssh tunnel using command-line ssh that connects port lport
    on this machine to localhost:rport on server.  The tunnel
    will automatically close when not in use, remaining open
    for a minimum of timeout seconds for an initial connection.

    This creates a tunnel redirecting `localhost:lport` to `remoteip:rport`,
    as seen from `server`.

    keyfile and password may be specified, but ssh config is checked for defaults.

    Parameters
    ----------

    lport : int
        local port for connecting to the tunnel from this machine.
    rport : int
        port on the remote machine to connect to.
    server : str
        The ssh server to connect to. The full ssh server string will be parsed.
        user@server:port
    remoteip : str [Default: 127.0.0.1]
        The remote ip, specifying the destination of the tunnel.
        Default is localhost, which means that the tunnel would redirect
        localhost:lport on this machine to localhost:rport on the *server*.

    keyfile : str; path to private key file
        This specifies a key to be used in ssh login, default None.
        Regular default ssh keys will be used without specifying this argument.
    password : str;
        Your ssh password to the ssh server. Note that if this is left None,
        you will be prompted for it if passwordless key based login is unavailable.
    timeout : int [default: 60]
        The time (in seconds) after which no activity will result in the tunnel
        closing.  This prevents orphaned tunnels from running forever.
    Nz(pexpect unavailable, use paramiko_tunnelzssh z-i ri   z -p z
 -O check T)withexitstatuss   (pid=      )z -O forward -L 127.0.0.1: z
-O forwardz	-O cancelr   z -f -S none -L 127.0.0.1:z sleep r.   r/   r0   Fr2   r3   r4   r   r6   zPassword rejected, try again's password: ztunnel 'z' failed to startr7   r8   )r9   r:   rk   runrl   findatexitregister_stop_tunnelreplacer;   r<   r=   r>   r?   r   r@   rA   r
   printr   sendlinerB   rC   
exitstatusbeforeafterRuntimeErrorpidr   )ro   rr   r(   rj   r)   rb   r5   sshr[   rD   outputr   r   r1   rE   rf   failedrG   rH   r   s                       r   rn   rn      s&   L DEEE
C uw
f}}||C((}d}}
$
$F
$
$C";s4@@@VZ &X..2V[[5F5FFGHHRRuRRxRR%RR&RR&{3tDDD 	OL#++lKQR*S*STTTJ
^
^5
^
^8
^
^e
^
^f
^
^U\
^
^C *//

CGGM4   ?J]3C(((FFI9  	z=93GGAAvv"I      4555"f#;#;#;<<OOH%%%FF#  	 	 	H{ 	" 	" 	"  "f'(((fm$$$fl###"#Dc#D#D#DEEEz!!!!!	"  ?9???
@
@@s   :3G--I.>A+I.-I.c                 .    t          j        |            d S N)r9   r{   )rD   s    r   r   r   -  s    Kr   c                     d| v r|                      dd          \  }} nt                      }d| v r(|                      d          \  } }t          |          }nd}|| |fS )N@r   ri      )rk   r   rl   )r(   rL   r[   s      r   rO   rO   1  sk    
f}}!<<Q//&&99
f}}||C((4yyVT!!r   c                    t           t          d          |"t          ||          st          | d          }t	          t
          | |||ft          ||                    }d|_        |                                 |S )a  launch a tunner with paramiko in a subprocess. This should only be used
    when shell ssh is unavailable (e.g. Windows).

    This creates a tunnel redirecting `localhost:lport` to `remoteip:rport`,
    as seen from `server`.

    If you are familiar with ssh tunnels, this creates the tunnel:

    ssh server -L localhost:lport:remoteip:rport

    keyfile and password may be specified, but ssh config is checked for defaults.


    Parameters
    ----------

    lport : int
        local port for connecting to the tunnel from this machine.
    rport : int
        port on the remote machine to connect to.
    server : str
        The ssh server to connect to. The full ssh server string will be parsed.
        user@server:port
    remoteip : str [Default: 127.0.0.1]
        The remote ip, specifying the destination of the tunnel.
        Default is localhost, which means that the tunnel would redirect
        localhost:lport on this machine to localhost:rport on the *server*.

    keyfile : str; path to private key file
        This specifies a key to be used in ssh login, default None.
        Regular default ssh keys will be used without specifying this argument.
    password : str;
        Your ssh password to the ssh server. Note that if this is left None,
        you will be prompted for it if passwordless key based login is unavailable.
    timeout : int [default: 60]
        The time (in seconds) after which no activity will result in the tunnel
        closing.  This prevents orphaned tunnels from running forever.

    NzParamiko not availablerz   )r)   rb   )targetargskwargsT)	r*   r:   r'   r   r   _paramiko_tunneldictdaemonstart)ro   rr   r(   rj   r)   rb   r5   rF   s           r   rm   rm   >  s    T 2333)&':: 	9&77788HUFH-Gh777	 	 	A
 AHGGIIIHr   c           	         t          |          \  }}}t          j                    }|                                 |                    t          j                               	 |                    ||||d|           nC# t          $ r6}	t          d| d| d|	           t          j
        d           Y d}	~	nd}	~	ww xY wt          j        t          j        t          j                   	 t          | |||                                           dS # t           $ r' t          d           t          j
        d	           Y dS t          $ r1}	t          d
|	            t          j
        d           Y d}	~	dS d}	~	ww xY w)zFunction for actually starting a paramiko tunnel, to be passed
    to multiprocessing.Process(target=this), and not called directly.
    T)rL   rM   rN   rb   z*** Failed to connect to ri   z: r   Nz'SIGINT: Port forwarding stopped cleanlyr   z#Port forwarding stopped uncleanly:    )rO   r*   rP   load_system_host_keysrW   WarningPolicyrX   	Exceptionr   r$   exitsignalSIGINTSIG_IGNr   get_transportKeyboardInterrupt)
ro   rr   r(   rj   r)   rb   rL   r[   r\   es
             r   r   r   y  s    +622Hfd!!F
  """
&&x'='?'?@@@  	 	
 	
 	
 	
    @&@@4@@1@@AAA
 M&-000uhv/C/C/E/EFFFFF   7888   7A77888s6   "A> >
B>,B99B>+$D -E;	E;
&E66E;r#   )rg   
ssh_tunnelrn   rm   r,   r   )NNNr`   )rt   NNr`   )NN))__doc__r}   r;   rer   r   r$   warningsr   r   multiprocessingr   catch_warningssimplefilterDeprecationWarningr*   ssh_exceptionr
   forwardr   r:   r   r9   r   r!   compile
IGNORECASErA   r,   r&   r'   rg   rc   rn   r   rO   rm   r   r%   r   __all__r   r   r   <module>r      s     				 				   



  $ $ $ $ $ $ $ $ # # # # # #(	 	 	"	" ; ;h(:;;;-:	; ; ; ; ; ; ; ; ; ; ; ; ; ; ; (''''''    H    y     NNNN   GGG	 	 	 	 	y 	 	 	  " 
0"-@@     A  A  AF  B OQ   . .  .  .  .H VX\A \A \A \A~  
" 
" 
" VX8 8 8 8v& & & &R <7 JJJ  sF   A= "A+A= +A//A= 2A/3A= =BBB B('B(