a b|}@s8dZddlmZddlZddlZddlZddlZddlZddlm Z m Z ddl m Z ddl mZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZmZm Z ddl!m"Z"ddl#m$Z$m%Z%Gddde%Z&Gddde'Z(Gddde(Z)Gddde(Z*Gddde(Z+dS)z SSH client & key policies )hexlifyN) ECONNREFUSED EHOSTUNREACH)Agent)DEBUG)SSH_PORT)DSSKey)ECDSAKey) Ed25519Key)HostKeys) string_types)RSAKey) SSHExceptionBadHostKeyExceptionNoValidConnectionsError) Transport)retry_on_signalClosingContextManagerc@seZdZdZddZd,ddZddZd d Zd d Zd dZ ddZ ddZ e ddddddddddddddddddfddZ ddZd-ddZd.d d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+ZdS)/ SSHClienta A high-level representation of a session with an SSH server. This class wraps `.Transport`, `.Channel`, and `.SFTPClient` to take care of most aspects of authenticating and opening channels. A typical use case is:: client = SSHClient() client.load_system_host_keys() client.connect('ssh.example.com') stdin, stdout, stderr = client.exec_command('ls -l') You may pass in explicit overrides for authentication and server host key checking. The default mechanism is to try to use local key files or an SSH agent (if one is running). Instances of this class may be used as context managers. .. versionadded:: 1.6 cCs4t|_t|_d|_d|_t|_d|_d|_dS)z) Create a new SSHClient. N) r _system_host_keys _host_keys_host_keys_filename _log_channel RejectPolicy_policy _transport_agentselfr6/tmp/pip-target-98j97qn4/lib/python/paramiko/client.py__init__EszSSHClient.__init__NcCsL|dur||!}||kr8|dur,t|"d}t#||||durJt$%}|durZg} nt&|t'rn|g} n|} |(|||| || | | ||j)| dS) a Connect to an SSH server and authenticate to it. The server's host key is checked against the system host keys (see `load_system_host_keys`) and any local host keys (`load_host_keys`). If the server's hostname is not found in either set of host keys, the missing host key policy is used (see `set_missing_host_key_policy`). The default policy is to reject the key and raise an `.SSHException`. Authentication is attempted in the following order of priority: - The ``pkey`` or ``key_filename`` passed in (if any) - ``key_filename`` may contain OpenSSH public certificate paths as well as regular private-key paths; when files ending in ``-cert.pub`` are found, they are assumed to match a private key, and both components will be loaded. (The private key itself does *not* need to be listed in ``key_filename`` for this to occur - *just* the certificate.) - Any key we can find through an SSH agent - Any "id_rsa", "id_dsa" or "id_ecdsa" key discoverable in ``~/.ssh/`` - When OpenSSH-style public certificates exist that match an existing such private key (so e.g. one has ``id_rsa`` and ``id_rsa-cert.pub``) the certificate will be loaded alongside the private key and used for authentication. - Plain username/password auth, if a password was given If a private key requires a password to unlock it, and a password is passed in, that password will be used to attempt to unlock the key. :param str hostname: the server to connect to :param int port: the server port to connect to :param str username: the username to authenticate as (defaults to the current local username) :param str password: Used for password authentication; is also used for private key decryption if ``passphrase`` is not given. :param str passphrase: Used for decrypting private keys. :param .PKey pkey: an optional private key to use for authentication :param str key_filename: the filename, or list of filenames, of optional private key(s) and/or certs to try for authentication :param float timeout: an optional timeout (in seconds) for the TCP connect :param bool allow_agent: set to False to disable connecting to the SSH agent :param bool look_for_keys: set to False to disable searching for discoverable private key files in ``~/.ssh/`` :param bool compress: set to True to turn on compression :param socket sock: an open socket or socket-like object (such as a `.Channel`) to use for communication to the target host :param bool gss_auth: ``True`` if you want to use GSS-API authentication :param bool gss_kex: Perform GSS-API Key Exchange and user authentication :param bool gss_deleg_creds: Delegate GSS-API client credentials or not :param str gss_host: The targets name in the kerberos database. default: hostname :param bool gss_trust_dns: Indicates whether or not the DNS is trusted to securely canonicalize the name of the host being connected to (default ``True``). :param float banner_timeout: an optional timeout (in seconds) to wait for the SSH banner to be presented. :param float auth_timeout: an optional timeout (in seconds) to wait for an authentication response. :param dict disabled_algorithms: an optional dict passed directly to `.Transport` and its keyword argument of the same name. :raises: `.BadHostKeyException` -- if the server's host key could not be verified :raises: `.AuthenticationException` -- if authentication failed :raises: `.SSHException` -- if there was any other error connecting or establishing an SSH session :raises socket.error: if a socket error occurred while connecting .. versionchanged:: 1.15 Added the ``banner_timeout``, ``gss_auth``, ``gss_kex``, ``gss_deleg_creds`` and ``gss_host`` arguments. .. versionchanged:: 2.3 Added the ``gss_trust_dns`` argument. .. versionchanged:: 2.4 Added the ``passphrase`` argument. .. versionchanged:: 2.6 Added the ``disabled_algorithms`` argument. Ncs SN)connectr)addrsockrr ]z#SSHClient.connect..)gss_kexgss_deleg_credsdisabled_algorithms)compress)gss_hostZ trust_dnsZgssapi_requestedz[{}]:{}rcsg|]}|kr|qSrr).0x)r3rr rPz%SSHClient.connect..timeout)*listrJr=r@ settimeoutrerrorerrnorrlenrrrZuse_compressionZ set_gss_hostrr8banner_timeout auth_timeoutrr/rgetrr2Zget_security_optionsZ key_typesZ start_client gss_kex_usedZget_remote_server_keyrmissing_host_keyget_namevaluesrgetpassgetuser isinstancer _authrU)!rr1rAusernamepasswordpkey key_filenamerZ allow_agent look_for_keysrTrNgss_authrQrRrUr`raZ gss_trust_dns passphraserSerrorsZto_tryafetZserver_hostkey_nameZour_server_keysZsec_optsZ other_typesZ server_keyZour_key key_filenamesr)rMr3rNr rLsw                          zSSHClient.connectcCs<|jdurdS|jd|_|jdur8|jd|_dS)a Close this SSHClient and its underlying `.Transport`. This should be called anytime you are done using the client object. .. warning:: Paramiko registers garbage collection hooks that will try to automatically close connections for you, but this is not presently reliable. Failure to explicitly close your client after use may lead to end-of-process hangs! N)rcloserrrrr rxs    zSSHClient.closec Csj|jj|d}|r||||r2|||||d|}|d|}|d|} ||| fS)a Execute a command on the SSH server. A new `.Channel` is opened and the requested command is executed. The command's input and output streams are returned as Python ``file``-like objects representing stdin, stdout, and stderr. :param str command: the command to execute :param int bufsize: interpreted the same way as by the built-in ``file()`` function in Python :param int timeout: set command's channel timeout. See `.Channel.settimeout` :param bool get_pty: Request a pseudo-terminal from the server (default ``False``). See `.Channel.get_pty` :param dict environment: a dict of shell environment variables, to be merged into the default environment that the remote command executes within. .. warning:: Servers may silently reject some environment variables; see the warning in `.Channel.set_environment_variable` for details. :return: the stdin, stdout, and stderr of the executing command, as a 3-tuple :raises: `.SSHException` -- if the server fails to execute the command .. versionchanged:: 1.10 Added the ``get_pty`` kwarg. rYwbr) r open_sessionget_ptyr\Zupdate_environment exec_commandZmakefile_stdinmakefileZmakefile_stderr) rcommandbufsizerZr} environmentchanstdinstdoutstderrrrr r~s(      zSSHClient.exec_commandvt100PrcCs(|j}||||||||S)a Start an interactive shell session on the SSH server. A new `.Channel` is opened and connected to a pseudo-terminal using the requested terminal type and size. :param str term: the terminal type to emulate (for example, ``"vt100"``) :param int width: the width (in characters) of the terminal window :param int height: the height (in characters) of the terminal window :param int width_pixels: the width (in pixels) of the terminal window :param int height_pixels: the height (in pixels) of the terminal window :param dict environment: the command's environment :return: a new `.Channel` connected to the remote shell :raises: `.SSHException` -- if the server fails to invoke a shell )rr|r} invoke_shell)rtermwidthheightZ width_pixelsZ height_pixelsrrrrr r s zSSHClient.invoke_shellcCs |jS)zn Open an SFTP session on the SSH server. :return: a new `.SFTPClient` session object )rZopen_sftp_clientrrrr open_sftp(szSSHClient.open_sftpcCs|jS)z Return the underlying `.Transport` object for this SSH connection. This can be used to perform lower-level tasks, like opening specific kinds of channels. :return: the `.Transport` for this connection )rrrrr get_transport0szSSHClient.get_transportc Csd}||r&|dt| }|}n |}||}|||}dt||}|t|tj |r| ||td||S)a7 Attempt to derive a `.PKey` from given string path ``filename``: - If ``filename`` appears to be a cert, the matching private key is loaded. - Otherwise, the filename is assumed to be a private key, and the matching public cert will be loaded if it exists. -cert.pubNzTrying discovered key {} in {}zAdding public certificate {}) endswithr_Zfrom_private_key_filer/rget_fingerprint_logrr"r#isfileZload_certificate) rr(klassrlZ cert_suffixZkey_pathZ cert_pathr4msgrrr _key_from_filepath:s       zSSHClient._key_from_filepathc  Cs:d} d} t}ddh}| dur*|dur*|} |rr|jjrrz|j|WdStyp}z|} WYd}~n d}~00|rz|j|| | WSty}z|} WYd}~n d}~00|dur,zD|tdt | t|j ||}||@} | sWdSWn*t y*}z|} WYd}~n d}~00| s|D]}t tttfD]v}zD|||| }t|j ||}||@} | sWdSWq6Wn*t y}z|} WYd}~n d}~00qFq6| sr|rr|jdurt|_|jD]}zRt | }|td|t|j ||}||@} | s8WdSWqrWn*t yl}z|} WYd}~n d}~00q| sg}t dftdftd ftd ffD]j\}}d D]Z}tjd ||}tj|r|||ftj|d r|||d fqq|sg}|D]|\}}zB|||| }t|j ||}||@} | sRWdSWqWn.t tfy}z|} WYd}~n d}~00q|durz|j||WdSt y}z|} WYd}~n d}~00nD| r z|j|WdSt y}z|} WYd}~n d}~00| dur.| t ddS)a Try, in order: - The key(s) passed in, if one was passed in. - Any key we can find through an SSH agent (if allowed). - Any "id_rsa", "id_dsa" or "id_ecdsa" key discoverable in ~/.ssh/ (if allowed). - Plain username/password auth, if a password was given. (The password might be needed to unlock a private key [if 'passphrase' isn't also given], or for two-factor authentication [for which it is required].) NFzkeyboard-interactiverlzTrying SSH key {}zTrying SSH agent key {}rsaZdsaZecdsaZed25519)z.sshsshz ~/{}/id_{}rz#No authentication methods available)setrrcZauth_gssapi_keyex ExceptionZauth_gssapi_with_micrrr/rrZauth_publickeyrr rr r rrrZget_keysr"r#r$rappendr&Z auth_passwordZauth_interactive_dumb)rrkrlrmrwrorprqrQrRrUrrZsaved_exceptionZ two_factorZ allowed_typesZtwo_factor_typesrurnZ pkey_classr4Zid_Zkeyfilesr3r7 directory full_pathr(rrr rjZs         "             zSSHClient._authcCs|j||dSrK)rr)rlevelrrrr rszSSHClient._log)N)ryNFN)rrrrrN)__name__ __module__ __qualname____doc__r!r)r*r5r6r8r<rJrrLrxr~rrrrrjrrrrr r1sb    h 6   (rc@seZdZdZddZdS)MissingHostKeyPolicya Interface for defining the policy that `.SSHClient` should use when the SSH server's hostname is not in either the system host keys or the application's keys. Pre-made classes implement policies for automatically adding the key to the application's `.HostKeys` object (`.AutoAddPolicy`), and for automatically rejecting the key (`.RejectPolicy`). This function may be used to ask the user to verify the key, for example. cCsdS)a Called when an `.SSHClient` receives a server key for a server that isn't in either the system or local `.HostKeys` object. To accept the key, simply return. To reject, raised an exception (which will be passed to the calling application). Nrrclientr1r4rrr rdsz%MissingHostKeyPolicy.missing_host_keyNrrrrrdrrrr rs rc@seZdZdZddZdS) AutoAddPolicyz Policy for automatically adding the hostname and new host key to the local `.HostKeys` object, and saving it. This is used by `.SSHClient`. c CsP|j||||jdur*||j|td||t| dS)NzAdding {} host key for {}: {}) raddrerr5rrr/rrrrrr rd s  zAutoAddPolicy.missing_host_keyNrrrrr rsrc@seZdZdZddZdS)rzk Policy for automatically rejecting the unknown hostname & key. This is used by `.SSHClient`. c Cs4|td||t|td|dS)Nz Rejecting {} host key for {}: {}z$Server {!r} not found in known_hosts)rrr/rerrrrrrr rd2szRejectPolicy.missing_host_keyNrrrrr r,src@seZdZdZddZdS) WarningPolicyz Policy for logging a Python-style warning for an unknown host key, but accepting it. This is used by `.SSHClient`. c Cs$td||t|dS)NzUnknown {} host key for {}: {})warningswarnr/rerrrrrr rdDs zWarningPolicy.missing_host_keyNrrrrr r>sr),rbinasciirrgr9r"r=rr^rrZparamiko.agentrZparamiko.commonrZparamiko.configrZparamiko.dsskeyrZparamiko.ecdsakeyr Zparamiko.ed25519keyr Zparamiko.hostkeysr Zparamiko.py3compatr Zparamiko.rsakeyr Zparamiko.ssh_exceptionrrrZparamiko.transportrZ paramiko.utilrrrobjectrrrrrrrr s:           Y