3 L]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)0 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_agent)selfr5/tmp/pip-install-wfra5znf/paramiko/paramiko/client.py__init__EszSSHClient.__init__Nc CsN|dkr>tjjd}y|jj|Wntk r8YnXdS|jj|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 expanduserrloadIOError)rfilenamerrrload_system_host_keysQs zSSHClient.load_system_host_keyscCs||_|jj|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$)rr&rrrload_host_keysnszSSHClient.load_host_keyscCsv|jdk r|j|jt|dL}xD|jjD]6\}}x,|jD] \}}|jdj|||jq@Wq.WWdQRXdS)aO Save the host keys back to a file. Only the host keys loaded with `load_host_keys` (plus any added directly) will be saved -- not any host keys loaded with `load_system_host_keys`. :param str filename: the filename to save to :raises: ``IOError`` -- if the file could not be written Nwz {} {} {} )rr(openritemswriteformatZ get_base64)rr&fhostnamekeyskeytypekeyrrrsave_host_keyss   zSSHClient.save_host_keyscCs|jS)z Get the local `.HostKeys` object. This can be used to examine the local host keys or change them. :return: the local host keys as a `.HostKeys` object. )r)rrrr get_host_keysszSSHClient.get_host_keyscCs ||_dS)z Set the channel for logging. The default is ``"paramiko.transport"`` but it can be set to anything you want. :param str name: new channel name for logging N)r)rnamerrrset_log_channelszSSHClient.set_log_channelcCstj|r|}||_dS)a Set policy to use when connecting to servers without a known host key. Specifically: * A **policy** is a "policy class" (or instance thereof), namely some subclass of `.MissingHostKeyPolicy` such as `.RejectPolicy` (the default), `.AutoAddPolicy`, `.WarningPolicy`, or a user-created subclass. * A host key is **known** when it appears in the client object's cached host keys structures (those manipulated by `load_system_host_keys` and/or `load_host_keys`). :param .MissingHostKeyPolicy policy: the policy to use when receiving a host key from a previously-unknown server N)inspectisclassr)rpolicyrrrset_missing_host_key_policys z%SSHClient.set_missing_host_key_policyc csrd}tj||tjtj}x.|D]&\}}}}} |tjkr|| fVd}qW|rnx |D]\}} } } } || fVqRWdS)a  Yield pairs of address families and addresses to try for connecting. :param str hostname: the server to connect to :param int port: the server port to connect to :returns: Yields an iterable of ``(family, address)`` tuples TFN)socket getaddrinfo AF_UNSPEC SOCK_STREAM) rr/portguessZ addrinfosfamilysocktypeproto canonnameZsockaddr_rrr_families_and_addressess  z!SSHClient._families_and_addressesTFc!ssi}t|j||}x|D]\}yJtj|tj|dk rZyj|Wn YnXtfddPWqtjk r}z|jtt fkr||<WYdd}~XqXqWt |t |krt |t | ||d}|_ |j| d|j|p||| p| d|jdk r|j|j|dk r.||_|dk r>||_|tkrN|}n dj||}d}|jj|}|dkr|jj|}|dk r|jd|j}fd d |jD}g||_|j|d |j js6|j}|dkr|jj |||n>|j|j!}||kr6|dkr*t|j"d}t#||||dkrHt$j%}|dkrXg} nt&|t'rl|g} n|} |j(|||| || | | ||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 jS)N)connectr)addrsockrr]sz#SSHClient.connect..)gss_kexgss_deleg_credsdisabled_algorithms)compress)gss_hostZ trust_dnsZgssapi_requestedz[{}]:{}rcsg|]}|kr|qSrr).0x)r1rr sz%SSHClient.connect..)timeout)*listrFr;r> settimeoutrerrorerrnorrlenrrrZuse_compressionZ set_gss_hostrr6banner_timeout auth_timeoutrr-rgetrr0Zget_security_optionsZ key_typesZ start_client gss_kex_usedZget_remote_server_keyrmissing_host_keyget_namevaluesrgetpassgetuser isinstancer _authrO)!rr/r?usernamepasswordpkey key_filenamerS allow_agent look_for_keysrNrIgss_authrKrLrOrYrZZ gss_trust_dns passphraserMerrorsZto_tryafetZserver_hostkey_nameZour_server_keysZsec_optsZ other_typesZ server_keyZour_key key_filenamesr)rHr1rIrrGsw                       zSSHClient.connectcCs<|jdkrdS|jjd|_|jdk r8|jjd|_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)rcloser)rrrrrqs    zSSHClient.closec Csj|jj|d}|r|j|j||r2|j||j||jd|}|jd|}|jd|} ||| 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. )rSwbr) r open_sessionget_ptyrUZupdate_environment exec_commandZmakefile_stdinmakefileZmakefile_stderr) rcommandbufsizerSrv environmentchanstdinstdoutstderrrrrrws(      zSSHClient.exec_commandvt100PrcCs(|jj}|j||||||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 )rrurv invoke_shell)rZtermwidthheightZ width_pixelsZ height_pixelsr{r|rrrrs zSSHClient.invoke_shellcCs |jjS)zn Open an SFTP session on the SSH server. :return: a new `.SFTPClient` session object )rZopen_sftp_client)rrrr 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 )r)rrrr get_transport.szSSHClient.get_transportc Csd}|j|r&|dt| }|}n |}||}|j||}djt|j|}|jt|tj j |r|j ||jtdj||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. z -cert.pubNzTrying discovered key {} in {}zAdding public certificate {}) endswithrXZfrom_private_key_filer-rget_fingerprint_logrr!r"isfileZload_certificate) rr&klassreZ cert_suffixZkey_pathZ cert_pathr2msgrrr_key_from_filepath8s      zSSHClient._key_from_filepathc <Csd} d} t}ddh}| dkr*|dk r*|} |rn|jjrny|jj|dStk rl}z |} WYdd}~XnX|ry|jj|| | Stk r}z |} WYdd}~XnX|dk ry@|jtdjt |j t|jj ||}||@} | sdSWn(t k r}z |} WYdd}~XnX| sx|D]}xxt tttfD]h}y8|j||| }t|jj ||}||@} | stdSPWn(t k r}z |} WYdd}~XnXqdSPWn,t tfk rn}z |} WYdd}~XnXqW|dk ry|jj||dSt k r}z |} WYdd}~XnXn@| ry|jj|dSt k r}z |} WYdd}~XnX| 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-interactiverezTrying SSH key {}zTrying SSH agent key {}ZrsaZdsaZecdsaZed25519.sshsshz ~/{}/id_{}z -cert.pubz#No authentication methods available)rr)setrr\Zauth_gssapi_keyex ExceptionZauth_gssapi_with_micrrr-rrZauth_publickeyrr rr r rrrZget_keysr!r"r#rappendr%Z auth_passwordZauth_interactive_dumb)rrdrerfrprhrirjrKrLrOrkZsaved_exceptionZ two_factorZ allowed_typesZtwo_factor_typesrnrgZ pkey_classr2Zid_Zkeyfilesr1r5 directory full_pathr&rrrrcXs      "       zSSHClient._authcCs|jj||dS)N)rr)rlevelrrrrrszSSHClient._log)N)rNFN)rrrrrN)__name__ __module__ __qualname____doc__r r'r(r3r4r6r:rFrrGrqrwrrrrrcrrrrrr1s\    S 0   (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). Nr)rclientr/r2rrrr]sz%MissingHostKeyPolicy.missing_host_keyN)rrrrr]rrrrrs 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`. cCsP|jj||j||jdk r*|j|j|jtdj|j|t|j dS)NzAdding {} host key for {}: {}) raddr^rr3rrr-rr)rrr/r2rrrr]s  zAutoAddPolicy.missing_host_keyN)rrrrr]rrrrrsrc@seZdZdZddZdS)rzk Policy for automatically rejecting the unknown hostname & key. This is used by `.SSHClient`. cCs4|jtdj|j|t|jtdj|dS)Nz Rejecting {} host key for {}: {}z$Server {!r} not found in known_hosts)rrr-r^rrr)rrr/r2rrrr]0s zRejectPolicy.missing_host_keyN)rrrrr]rrrrr*src@seZdZdZddZdS) WarningPolicyz Policy for logging a Python-style warning for an unknown host key, but accepting it. This is used by `.SSHClient`. cCs$tjdj|j|t|jdS)NzUnknown {} host key for {}: {})warningswarnr-r^rr)rrr/r2rrrr]BszWarningPolicy.missing_host_keyN)rrrrr]rrrrr<sr),rbinasciirr`r7r!r;rrWrrZparamiko.agentrZparamiko.commonrZparamiko.configrZparamiko.dsskeyrZparamiko.ecdsakeyr Zparamiko.ed25519keyr Zparamiko.hostkeysr Zparamiko.py3compatr Zparamiko.rsakeyr Zparamiko.ssh_exceptionrrrZparamiko.transportrZ paramiko.utilrrrobjectrrrrrrrrs:           W