_e[c@sdZddlmZddlZddlZddlZddlZddlZddlm Z m Z ddl m Z ddl mZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZmZm Z ddl!m"Z"ddl#m$Z$m%Z%de%fdYZ&de'fdYZ(de(fdYZ)de(fdYZ*de(fdYZ+dS(s SSH client & key policies i(thexlifyN(t ECONNREFUSEDt EHOSTUNREACH(tAgent(tDEBUG(tSSH_PORT(tDSSKey(tECDSAKey(t Ed25519Key(tHostKeys(t string_types(tRSAKey(t SSHExceptiontBadHostKeyExceptiontNoValidConnectionsError(t Transport(tretry_on_signaltClosingContextManagert SSHClientcBseZdZdZddZdZdZdZdZ dZ dZ e ddddde e edeee ddde dd Zd Zd dedd Zd ddddddZdZdZdZdZdZRS(s 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 cCsLt|_t|_d|_d|_t|_d|_d|_ dS(s) Create a new SSHClient. N( R t_system_host_keyst _host_keystNonet_host_keys_filenamet _log_channelt RejectPolicyt_policyt _transportt_agent(tself((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyt__init__Cs      cCs^|dkrJtjjd}y|jj|Wntk rEnXdS|jj|dS(s 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 s~/.ssh/known_hostsN(Rtostpatht expanduserRtloadtIOError(Rtfilename((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pytload_system_host_keysOs  cCs||_|jj|dS(s 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#((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pytload_host_keysls c Cs|jdk r"|j|jnt|df}x\|jjD]K\}}x<|jD].\}}|jdj|||jq]WqDWWdQXdS(sO 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 tws {} {} {} N( RRR%topenRtitemstwritetformatt get_base64(RR#tfthostnametkeystkeytypetkey((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pytsave_host_keyss  cCs|jS(s 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(R((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyt get_host_keysscCs ||_dS(s 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(Rtname((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pytset_log_channelscCs(tj|r|}n||_dS(s 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(tinspecttisclassR(Rtpolicy((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pytset_missing_host_key_policys c cst}tj||tjtj}x@|D]8\}}}}} |tjkr+|| fVt}q+q+W|rx+|D] \}} } } } || fVqtWndS(s  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 N(tTruetsockett getaddrinfot AF_UNSPECt SOCK_STREAMtFalse( RR-tporttguesst addrinfostfamilytsocktypetprotot canonnametsockaddrt_((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyt_families_and_addressess  c" ssi}t|j||}x|D]\}yZtj|tj|d k ryyj|WqyqyXntfdPWq+tjk r}|jt t fkrn|||d|d| pP| |jd k rv|j|jn|d k r||_n|d k r||_n|tkr|}ndj||}d }|jj|}|d kr|jj|}n|d k ri|jd }|j}g|jD]}||kr8|^q8}|g||_n|jd ||jjs|j}|d kr|j j!|||q|j|j"} | |kr| d krt|j#d } nt$||| qn|d kr/t%j&}n|d krDg}!n!t'|t(r_|g}!n|}!|j)||||!|| | | ||j*| d S( s 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. :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. cs jS(N(tconnect((taddrtsock(s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pytRstgss_kextgss_deleg_credstcompresstgss_hostt trust_dnstgssapi_requesteds[{}]:{}ittimeoutN(+tlistRHR:R=Rt settimeoutRterrorterrnoRRtlenRRRtuse_compressiont set_gss_hostRR4tbanner_timeoutt auth_timeoutRR*RtgetRR.tget_security_optionst key_typest start_clientt gss_kex_usedtget_remote_server_keyRtmissing_host_keytget_nametvaluesR tgetpasstgetusert isinstanceR t_authRP("RR-R?tusernametpasswordtpkeyt key_filenameRSt allow_agentt look_for_keysRORKtgss_authRMRNRPR[R\t gss_trust_dnst passphraseterrorstto_trytaftetttserver_hostkey_nametour_server_keysR/tsec_optstxt other_typest server_keytour_keyt key_filenames((RJRKs3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyRIsq             (          cCsU|jdkrdS|jjd|_|jdk rQ|jjd|_ndS(s 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(RRtcloseR(R((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyRs    ic Cs|jjd|}|r(|jn|j||rK|j|n|j||jd|}|jd|}|jd|} ||| fS(sI 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 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 RStwbtr(Rt open_sessiontget_ptyRUtupdate_environmentt exec_commandtmakefiletmakefile_stderr( RtcommandtbufsizeRSRt environmenttchantstdintstdouttstderr((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyRs"   tvt100iPiicCs6|jj}|j||||||j|S(s 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 (RRRt invoke_shell(Rttermtwidththeightt width_pixelst height_pixelsRR((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyRs cCs |jjS(sn Open an SFTP session on the SSH server. :return: a new `.SFTPClient` session object (Rtopen_sftp_client(R((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyt open_sftpscCs|jS(s 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(R((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyt get_transport sc Csd}|j|r/|t| }|}n|}||}|j||}djt|j|}|jt|tj j |r|j ||jtdj|n|S(s7 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. s -cert.pubsTrying discovered key {} in {}sAdding public certificate {}( tendswithRXtfrom_private_key_fileR*Rtget_fingerprintt_logRRRtisfiletload_certificate( RR#tklassRkt cert_suffixtkey_patht cert_pathR0tmsg((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyt_key_from_filepaths    c Csd} t} t}ddh}| dkrB|dk rB|} n|r|jjry|jj|dSWqtk r}|} qXn|ry|jj|| | SWqtk r}|} qXn|dk rMyX|jt dj t |j t|jj ||}||@} | s-dSWqMtk rI}|} qMXn| sx|D]}xttttfD]k}yI|j||| }t|jj ||}||@} | sdSPWqstk r}|} qsXqsWqZWn| r|r|jdkrt|_nx|jjD]}y_t |j }|jt dj |t|jj ||}||@} | sdSPWq$tk r}|} q$Xq$Wn| sg}xtdftdftdftd fgD]\}}xd d gD]|}tjjd j ||}tjj|r|j||ftjj|d rx|j||d fqxqqWqW|sg}nx|D]w\}}yI|j||| }t|jj ||}||@} | sdSPWqttfk r }|} qXqWn|dk rZy|jj||dSWqtk rV}|} qXn=| ry|jj|dSWqtk r}|} qXn| dk r| ntddS(s 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].) skeyboard-interactiveRkNsTrying SSH key {}sTrying SSH agent key {}trsatdsatecdsated25519s.sshtsshs ~/{}/id_{}s -cert.pubs#No authentication methods available(RR>tsetRRatauth_gssapi_keyext Exceptiontauth_gssapi_with_micRRR*RRtauth_publickeyR R RRRRRRtget_keysRRR RtappendR"t auth_passwordtauth_interactive_dumb(RRjRkRlRRnRoRpRMRNRPRrtsaved_exceptiont two_factort allowed_typesttwo_factor_typesRvRmt pkey_classR0tid_tkeyfilesR/R3t directoryt full_pathR#((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyRi5s                 %       cCs|jj||dS(N(RR(RtlevelR((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyRsN(t__name__t __module__t__doc__RRR$R%R1R2R4R8RHRR9R>RIRRRRRRRiR(((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyR/sN       (   tMissingHostKeyPolicycBseZdZdZRS(s 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(s 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). N((RtclientR-R0((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyRcs(RRRRc(((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyRs t AutoAddPolicycBseZdZdZRS(s Policy for automatically adding the hostname and new host key to the local `.HostKeys` object, and saving it. This is used by `.SSHClient`. cCss|jj||j||jdk r>|j|jn|jtdj|j|t |j dS(NsAdding {} host key for {}: {}( RtaddRdRRR1RRR*RR(RRR-R0((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyRcs (RRRRc(((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyRsRcBseZdZdZRS(sk Policy for automatically rejecting the unknown hostname & key. This is used by `.SSHClient`. cCsJ|jtdj|j|t|jtdj|dS(Ns Rejecting {} host key for {}: {}s$Server {!r} not found in known_hosts(RRR*RdRRR (RRR-R0((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyRcs"(RRRRc(((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyRst WarningPolicycBseZdZdZRS(s Policy for logging a Python-style warning for an unknown host key, but accepting it. This is used by `.SSHClient`. cCs2tjdj|j|t|jdS(NsUnknown {} host key for {}: {}(twarningstwarnR*RdRR(RRR-R0((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyRc s (RRRRc(((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyRs(,RtbinasciiRRfR5RR:RRWRRtparamiko.agentRtparamiko.commonRtparamiko.configRtparamiko.dsskeyRtparamiko.ecdsakeyRtparamiko.ed25519keyRtparamiko.hostkeysR tparamiko.py3compatR tparamiko.rsakeyR tparamiko.ssh_exceptionR R Rtparamiko.transportRt paramiko.utilRRRtobjectRRRR(((s3/tmp/pip-install-KP2Jbq/paramiko/paramiko/client.pyts4