U vf@s&dZddlmZddlZddlZddlZddlZddlZddlm Z m Z ddl m Z ddl mZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZmZmZddlm Z ddl!m"Z"Gddde"Z#GdddZ$Gddde$Z%Gddde$Z&Gddde$Z'dS)z SSH client & key policies )hexlifyN) ECONNREFUSED EHOSTUNREACH)Agent)DEBUG)SSH_PORT)DSSKey)ECDSAKey) Ed25519Key)HostKeys)RSAKey) SSHExceptionBadHostKeyExceptionNoValidConnectionsError) Transport)ClosingContextManagerc@seZdZdZddZd,ddZddZd d Zd d Zd dZ ddZ ddZ e dddddddddddddddddddddfddZ 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_agentselfr@/opt/alt/python38/lib/python3.8/site-packages/paramiko/client.py__init__DszSSHClient.__init__NcCsN|dkr>tjd}z|j|Wntk r8YnXdS|j|dS)a Load host keys from a system (read-only) file. Host keys read with this method will not be saved back by `save_host_keys`. This method can be called multiple times. Each new set of host keys will be merged with the existing set (new replacing old if there are conflicts). If ``filename`` is left as ``None``, an attempt will be made to read keys from the user's local "known hosts" file, as used by OpenSSH, and no exception will be raised if the file can't be read. This is probably only useful on posix. :param str filename: the filename to read, or ``None`` :raises: ``IOError`` -- if a filename was provided and the file could not be read Nz~/.ssh/known_hosts)ospath expanduserrloadIOErrorrfilenamerrrload_system_host_keysPs zSSHClient.load_system_host_keyscCs||_|j|dS)a Load host keys from a local host-key file. Host keys read with this method will be checked after keys loaded via `load_system_host_keys`, but will be saved back by `save_host_keys` (so they can be modified). The missing host key policy `.AutoAddPolicy` adds keys to this set and saves them, when connecting to a previously-unknown server. This method can be called multiple times. Each new set of host keys will be merged with the existing set (new replacing old if there are conflicts). When automatically saving, the last hostname is used. :param str filename: the filename to read :raises: ``IOError`` -- if the filename could not be read N)rrr#r%rrrload_host_keysmszSSHClient.load_host_keysc Csn|jdk r||jt|dD}|jD]2\}}|D] \}}|d|||q||"#}#|#|"krX|#dkrLt|$d}#t%||"|#|dkrjt&'}|dk r|j(|d S|dkrg}$nt)|t*r|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 float channel_timeout: an optional timeout (in seconds) to wait for a channel open response. :param dict disabled_algorithms: an optional dict passed directly to `.Transport` and its keyword argument of the same name. :param transport_factory: an optional callable which is handed a subset of the constructor arguments (primarily those related to the socket, GSS functionality, and algorithm selection) and generates a `.Transport` instance to be used by this client. Defaults to `.Transport.__init__`. :param auth_strategy: an optional instance of `.AuthStrategy`, triggering use of this newer authentication mechanism instead of SSHClient's legacy auth method. .. warning:: This parameter is **incompatible** with all other authentication-related parameters (such as, but not limited to, ``password``, ``key_filename`` and ``allow_agent``) and will trigger an exception if given alongside them. :returns: `.AuthResult` if ``auth_strategy`` is non-``None``; otherwise, returns ``None``. :raises BadHostKeyException: if the server's host key could not be verified. :raises AuthenticationException: if authentication failed. :raises UnableToAuthenticate: if authentication failed (when ``auth_strategy`` is non-``None``; and note that this is a subclass of ``AuthenticationException``). :raises socket.error: if a socket error (other than connection-refused or host-unreachable) occurred while connecting. :raises NoValidConnectionsError: if all valid connection targets for the requested hostname (eg IPv4 and IPv6) yielded connection-refused or host-unreachable socket errors. :raises SSHException: if there was any other error connecting or establishing an SSH session. .. 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. .. versionchanged:: 2.12 Added the ``transport_factory`` argument. .. versionchanged:: 3.2 Added the ``auth_strategy`` argument. N)gss_kexgss_deleg_credsdisabled_algorithms)compress)gss_hostZ trust_dnsZgssapi_requestedz[{}]:{}rcsg|]}|kr|qSrr).0xr1rr sz%SSHClient.connect..timeout) transport)-listrHr;r> settimeoutconnecterrorcloseerrnorrlenrrrZuse_compressionZ set_gss_hostrr6banner_timeout auth_timeoutchannel_timeoutrr-rgetrr0Zget_security_optionsZ key_typesZ start_client gss_kex_usedZget_remote_server_keyrmissing_host_keyget_namevaluesrgetpassgetuserZ authenticate isinstancestr_authrM)%rr/r?usernamepasswordpkey key_filenamerS allow_agent look_for_keysrLsockgss_authrIrJrMr\r]r^Z gss_trust_dns passphraserKZtransport_factoryZ auth_strategyerrorsZto_tryafaddretZserver_hostkey_nameZour_server_keysZsec_optsZ other_typesZ server_keyZour_key key_filenamesrrPrrWs                             zSSHClient.connectcCs<|jdkrdS|jd|_|jdk r8|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)rrYrrrrrrYs    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. rRwbr) r open_sessionget_ptyrVZupdate_environment exec_commandZmakefile_stdinmakefileZmakefile_stderr) rcommandbufsizerSr| environmentchanstdinstdoutstderrrrrr}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_pixelsrrrrrr<s zSSHClient.invoke_shellcCs |jS)zn Open an SFTP session on the SSH server. :return: a new `.SFTPClient` session object )rZopen_sftp_clientrrrr open_sftpZszSSHClient.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_transportbszSSHClient.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&klassrjZ cert_suffixZkey_pathZ cert_pathr2msgrrr_key_from_filepathls       zSSHClient._key_from_filepathc  Cs*d} d} t}ddh}| dkr*|dk r*|} |rp|jjrpz|j|WdStk rn}z|} W5d}~XYnX|rz|j|| | WStk r}z|} W5d}~XYnX|dk r&zD|tdt | t|j ||}||@} | sWdSWn(t k r$}z|} W5d}~XYnX| s|D]}t tttfD]t}zD|||| }t|j ||}||@} | s~WdSWq0Wn(t k r}z|} W5d}~XYnXq@q0| sh|rh|jdkrt|_|jD]}zRt | }|td|t|j ||}||@} | s0WdSWqhWn(t k rb}z|} W5d}~XYnXq| sg}t dftdftd ftd ffD]j\}}d D]Z}tjd ||}tj|r|||ftj|d r|||d fqq|sg}|D]z\}}zB|||| }t|j ||}||@} | sHWdSWqWn,t tfk r~}z|} W5d}~XYnXq|dk rz|j||WdSt k r}z|} W5d}~XYnXnB| rz|j|WdSt k r}z|} W5d}~XYnX| dk r| 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-interactiverjzTrying SSH key {}zTrying SSH agent key {}rsaZdsaZecdsaZed25519)z.sshsshz ~/{}/id_{}rz#No authentication methods available)setrr`Zauth_gssapi_keyex ExceptionZauth_gssapi_with_micrrr-rrZauth_publickeyr r rr r rrrZget_keysr r!r"rappendr$Z auth_passwordZauth_interactive_dumb)rrirjrkrwrmrnrprIrJrMrqZsaved_exceptionZ two_factorZ allowed_typesZtwo_factor_typesrurlZ pkey_classr2Zid_Zkeyfilesr1r5 directory full_pathr&rrrrhs                      zSSHClient._authcCs|j||dS)N)rr)rlevelrrrrr5szSSHClient._log)N)rxNFN)rrrrrN)__name__ __module__ __qualname____doc__rr'r(r3r4r6r:rHrrWrYr}rrrrrhrrrrrr0sj     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). Nrrclientr/r2rrrraDsz%MissingHostKeyPolicy.missing_host_keyNrrrrrarrrrr9s 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||||jdk r*||j|td||t| dS)NzAdding {} host key for {}: {}) raddrbrr3rrr-rrrrrrraTs   zAutoAddPolicy.missing_host_keyNrrrrrrNsrc@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-rbrrr rrrrrafs zRejectPolicy.missing_host_keyNrrrrrr`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-rbrrrrrrraxs zWarningPolicy.missing_host_keyNrrrrrrrsr)(rbinasciirrdr7r r;rrZrrZparamiko.agentrZparamiko.commonrZparamiko.configrZparamiko.dsskeyrZparamiko.ecdsakeyr Zparamiko.ed25519keyr Zparamiko.hostkeysr Zparamiko.rsakeyr Zparamiko.ssh_exceptionr rrZparamiko.transportrZ paramiko.utilrrrrrrrrrrs: