U q`G}@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-nv4zd3e_/lib/python/paramiko/client.py__init__EszSSHClient.__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 expanduserrloadIOErrorrfilenamerrr load_system_host_keysQs 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'rrr load_host_keysnszSSHClient.load_host_keysc Csn|jdk r||jt|dD}|jD]2\}}|D] \}}|d|||q||!}||kr4|dkr(t|"d}t#||||dkrFt$%}|dkrVg} nt&|t'rj|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 sz%SSHClient.connect..timeout)*listrHr=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 _authrS)!rr1rAusernamepasswordpkey key_filenamerX allow_agent look_for_keysrRrLgss_authrOrPrSr^r_Z gss_trust_dns passphraserQerrorsZto_tryafetZserver_hostkey_nameZour_server_keysZsec_optsZ other_typesZ server_keyZour_key key_filenamesr)rKr3rLr rJsw                         zSSHClient.connectcCs<|jdkrdS|jd|_|jdk r8|jd|_dS)a Close this SSHClient and its underlying `.Transport`. .. warning:: Failure to do this may, in some situations, cause your Python interpreter to hang at shutdown (often due to race conditions). It's good practice to `close` your client objects anytime you're done using them, instead of relying on garbage collection. N)rcloserrrrr rvs    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. rWwbr) r open_sessionget_ptyrZZupdate_environment exec_commandZmakefile_stdinmakefileZmakefile_stderr) rcommandbufsizerXr{ 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 )rrzr{ invoke_shell)rZtermwidthheightZ width_pixelsZ height_pixelsrrrrr rs 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_transport.szSSHClient.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_pathr4msgrrr _key_from_filepath8s       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)setrraZauth_gssapi_keyex ExceptionZauth_gssapi_with_micrrr/rrZauth_publickeyrr rr r rrrZget_keysr"r#r$rappendr&Z auth_passwordZauth_interactive_dumb)rrirjrkrurmrnrorOrPrSrpZsaved_exceptionZ two_factorZ allowed_typesZtwo_factor_typesrsrlZ pkey_classr4Zid_Zkeyfilesr3r7 directory full_pathr(rrr rhXs                      zSSHClient._authcCs|j||dSrI)rr)rlevelrrrr rszSSHClient._log)N)rwNFN)rrrrrN)__name__ __module__ __qualname____doc__r!r)r*r5r6r8r<rHrrJrvr|rrrrrhrrrrr 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 rbsz%MissingHostKeyPolicy.missing_host_keyNrrrrrbrrrr 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||||jdk r*||j|td||t| dS)NzAdding {} host key for {}: {}) raddrcrr5rrr/rrrrrr rbs   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/rcrrrrrrr rb0s zRejectPolicy.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/rcrrrrrr rbBs zWarningPolicy.missing_host_keyNrrrrr r<sr),rbinasciirrer9r"r=rr\rrZparamiko.agentrZparamiko.commonrZparamiko.configrZparamiko.dsskeyrZparamiko.ecdsakeyr Zparamiko.ed25519keyr Zparamiko.hostkeysr Zparamiko.py3compatr Zparamiko.rsakeyr Zparamiko.ssh_exceptionrrrZparamiko.transportrZ paramiko.utilrrrobjectrrrrrrrr s:           W