=OXc@sddlmZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z ddlmZmZmZddlmZmZmZmZmZmZddlmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7dd l8m9Z9dd l:m;Z;dd l<m=Z=dd l>m?Z?d Z@dZAdee?fdYZBdeBfdYZCdS(i(thexlifyN(tutil(tChannel(tMessage(tINFOtDEBUGto777(t bytestringtbtutlongt string_typest bytes_types(tBaseSFTPt CMD_OPENDIRt CMD_HANDLEt SFTPErrort CMD_READDIRtCMD_NAMEt CMD_CLOSEtSFTP_FLAG_READtSFTP_FLAG_WRITEtSFTP_FLAG_CREATEtSFTP_FLAG_TRUNCtSFTP_FLAG_APPENDtSFTP_FLAG_EXCLtCMD_OPENt CMD_REMOVEt CMD_RENAMEt CMD_MKDIRt CMD_RMDIRtCMD_STATt CMD_ATTRSt CMD_LSTATt CMD_SYMLINKt CMD_SETSTATt CMD_READLINKt CMD_REALPATHt CMD_STATUStSFTP_OKtSFTP_EOFtSFTP_NO_SUCH_FILEtSFTP_PERMISSION_DENIED(tSFTPAttributes(t SSHException(tSFTPFile(tClosingContextManagercCsUy|jdSWn=ttfk rPy|jdSWqQtk rL|SXnXdS(s decode a string as ascii or utf8 if possible (as required by the sftp protocol). if neither works, just return a byte string because the server probably doesn't know the filename's encoding. tasciisutf-8N(tencodet UnicodeErrortAttributeErrortdecode(ts((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyt _to_unicode-s t/t SFTPClientcBseZdZdZed)d)dZdZdZdZ ddZ ddZ dd d Z d d d Z e ZdZeZdZedZdZdZdZdZdZdZdZdZdZdZd)dZdZdZ dd)e!dZ"d)e!d Z#d)d!Z$d)d"Z%d#Z&d$Z'd)d%Z(d&Z)d'Z*d(Z+RS(*s SFTP client object. Used to open an SFTP session across an open SSH `.Transport` and perform remote file operations. Instances of this class may be used as context managers. cCstj|||_t|_d|_tj|_d|_ t j |_ t|tkr|jj}tj|jd|_|j|_ny|j}Wntk rtdnX|jtd|dS(s Create an SFTP client from an existing `.Channel`. The channel should already have requested the ``"sftp"`` subsystem. An alternate way to create an SFTP client context is by using `from_transport`. :param .Channel sock: an open `.Channel` using the ``"sftp"`` subsystem :raises SSHException: if there's an exception while negotiating sftp is.sftpsEOF during negotiations*Opened sftp connection (server version %d)N(R t__init__tsocktFalset ultra_debugtrequest_numbert threadingtLockt_locktNonet_cwdtweakreftWeakValueDictionaryt _expectingttypeRt get_transportRt get_loggertget_log_channeltloggert get_hexdumpt _send_versiontEOFErrorR,t_logR(tselfR9t transporttserver_version((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyR8Gs      cCs?|jd|d|}|dkr(dS|jd||S(sP Create an SFTP client channel from an open `.Transport`. Setting the window and packet sizes might affect the transfer speed. The default settings in the `.Transport` class are the same as in OpenSSH and should work adequately for both files transfers and interactive sessions. :param .Transport t: an open `.Transport` which is already authenticated :param int window_size: optional window size for the `.SFTPClient` session. :param int max_packet_size: optional max packet size for the `.SFTPClient` session.. :return: a new `.SFTPClient` object, referring to an sftp session (channel) across the transport .. versionchanged:: 1.15 Added the ``window_size`` and ``max_packet_size`` arguments. t window_sizetmax_packet_sizetsftpN(t open_sessionR@tinvoke_subsystem(tclsttRQRRtchan((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytfrom_transporths    cGst|tr6xl|D]}|j|||qWnH|jdd}tt|j|d||jjgt|dS(Nt%s%%s [chan %s] (t isinstancetlistRMtreplacetsuperR7R9tget_name(RNtleveltmsgtargstm((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyRMs  cCs!|jtd|jjdS(sc Close the SFTP session and its underlying channel. .. versionadded:: 1.4 ssftp session closed.N(RMRR9tclose(RN((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyRdscCs|jS(s Return the underlying `.Channel` object for this SFTP session. This might be useful for doing things like setting a timeout on the channel. .. versionadded:: 1.7.1 (R9(RN((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyt get_channelst.cCs#g|j|D]}|j^qS(s Return a list containing the names of the entries in the given ``path``. The list is in arbitrary order. It does not include the special entries ``'.'`` and ``'..'`` even if they are present in the folder. This method is meant to mirror ``os.listdir`` as closely as possible. For a list of full `.SFTPAttributes` objects, see `listdir_attr`. :param str path: path to list (defaults to ``'.'``) (t listdir_attrtfilename(RNtpathtf((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytlistdirs c CsM|j|}|jtd||jt|\}}|tkrVtdn|j}g}xtr8y|jt |\}}Wnt k rPnX|t krtdn|j }xit |D][}|j}|j} tj||| } |dkr|dkr|j| qqWqkW|jt||S(s Return a list containing `.SFTPAttributes` objects corresponding to files in the given ``path``. The list is in arbitrary order. It does not include the special entries ``'.'`` and ``'..'`` even if they are present in the folder. The returned `.SFTPAttributes` objects will each have an additional field: ``longname``, which may contain a formatted string of the file's attributes, in unix format. The content of this string will probably depend on the SFTP server implementation. :param str path: path to list (defaults to ``'.'``) :return: list of `.SFTPAttributes` objects .. versionadded:: 1.2 s listdir(%r)sExpected handlesExpected name responseRfs..(t _adjust_cwdRMRt_requestRRRt get_binarytTrueRRLRtget_inttrangetget_textR+t _from_msgtappendR( RNRiRWRathandletfilelisttcounttiRhtlongnametattr((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyRgs.        i2ccs|j|}|jtd||jt|\}}|tkrVtdn|j}t}xQt ry"x<t |D].}|j t dt|}|j|qWx|D]}|j\}} t| }|j} || kr|tkr|j|qn|j} xat | D]S}|j} |j} tj|| | }| dkr1| dkr1|Vq1q1WqWt}Wqntk r|jt|dSXqnWdS(s Generator version of `.listdir_attr`. See the API docs for `.listdir_attr` for overall details. This function adds one more kwarg on top of `.listdir_attr`: ``read_aheads``, an integer controlling how many ``SSH_FXP_READDIR`` requests are made to the server. The default of 50 should suffice for most file listings as each request/response cycle may contain multiple files (dependant on server implementation.) .. versionadded:: 1.15 s listdir(%r)sExpected handleRfs..N(RlRMRRmRRRt get_stringR\RoRqt_async_requestRER@RRtt _read_packetRRpR&t_convert_statusRrR+RsRLR(RNRit read_aheadsRWRaRutnumsRxtnumtpkt_datatnew_numRwRhRyRz((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyt listdir_iters>              tric Cs`|j|}|jtd||fd}d|ksGd|krT|tO}nd|ksxd|ksxd|kr|tO}nd|kr|ttBO}nd|kr|ttBO}nd|kr|ttBO}nt }|j t |||\}}|t krt dn|j}|jtd ||t|ft||||S( sT Open a file on the remote server. The arguments are the same as for Python's built-in `python:file` (aka `python:open`). A file-like object is returned, which closely mimics the behavior of a normal Python file object, including the ability to be used as a context manager. The mode indicates how the file is to be opened: ``'r'`` for reading, ``'w'`` for writing (truncating an existing file), ``'a'`` for appending, ``'r+'`` for reading/writing, ``'w+'`` for reading/writing (truncating an existing file), ``'a+'`` for reading/appending. The Python ``'b'`` flag is ignored, since SSH treats all files as binary. The ``'U'`` flag is supported in a compatible way. Since 1.5.2, an ``'x'`` flag indicates that the operation should only succeed if the file was created and did not previously exist. This has no direct mapping to Python's file flags, but is commonly known as the ``O_EXCL`` flag in posix. The file will be buffered in standard Python style by default, but can be altered with the ``bufsize`` parameter. ``0`` turns off buffering, ``1`` uses line buffering, and any number greater than 1 (``>1``) uses that specific buffer size. :param str filename: name of the file to open :param str mode: mode (Python-style) to open in :param int bufsize: desired buffering (-1 = default buffer size) :return: an `.SFTPFile` object representing the open file :raises IOError: if the file could not be opened. s open(%r, %r)iRt+twtatxsExpected handlesopen(%r, %r) -> %s(RlRMRRRRRRRR+RmRRRRnRR-( RNRhtmodetbufsizetimodet attrblockRWRaRu((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytopens(  $       #cCs7|j|}|jtd||jt|dS(s Remove the file at the given path. This only works on files; for removing folders (directories), use `rmdir`. :param str path: path (absolute or relative) of the file to remove :raises IOError: if the path refers to a folder (directory) s remove(%r)N(RlRMRRmR(RNRi((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytremoveQs cCsO|j|}|j|}|jtd||f|jt||dS(s& Rename a file or folder from ``oldpath`` to ``newpath``. :param str oldpath: existing name of the file or folder :param str newpath: new name for the file or folder :raises IOError: if ``newpath`` is a folder, or something else goes wrong srename(%r, %r)N(RlRMRRmR(RNtoldpathtnewpath((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytrename`s cCsR|j|}|jtd||ft}||_|jt||dS(ss Create a folder (directory) named ``path`` with numeric mode ``mode``. The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out. :param str path: name of the folder to create :param int mode: permissions (posix-style) for the newly-created folder s mkdir(%r, %r)N(RlRMRR+tst_modeRmR(RNRiRRz((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytmkdiros   cCs7|j|}|jtd||jt|dS(sj Remove the folder named ``path``. :param str path: name of the folder to remove s rmdir(%r)N(RlRMRRmR(RNRi((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytrmdir~scCsc|j|}|jtd||jt|\}}|tkrVtdntj|S(s8 Retrieve information about a file on the remote system. The return value is an object whose attributes correspond to the attributes of Python's ``stat`` structure as returned by ``os.stat``, except that it contains fewer fields. An SFTP server may return as much or as little info as it wants, so the results may vary from server to server. Unlike a Python `python:stat` object, the result may not be accessed as a tuple. This is mostly due to the author's slack factor. The fields supported are: ``st_mode``, ``st_size``, ``st_uid``, ``st_gid``, ``st_atime``, and ``st_mtime``. :param str path: the filename to stat :return: an `.SFTPAttributes` object containing attributes about the given file sstat(%r)sExpected attributes( RlRMRRmRR RR+Rs(RNRiRWRa((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytstats  cCsc|j|}|jtd||jt|\}}|tkrVtdntj|S(sZ Retrieve information about a file on the remote system, without following symbolic links (shortcuts). This otherwise behaves exactly the same as `stat`. :param str path: the filename to stat :return: an `.SFTPAttributes` object containing attributes about the given file s lstat(%r)sExpected attributes( RlRMRRmR!R RR+Rs(RNRiRWRa((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytlstats  cCsL|j|}|jtd||ft|}|jt||dS(s Create a symbolic link (shortcut) of the ``source`` path at ``destination``. :param str source: path of the original file :param str dest: path of the newly created symlink ssymlink(%r, %r)N(RlRMRRRmR"(RNtsourcetdest((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytsymlinks cCsR|j|}|jtd||ft}||_|jt||dS(s Change the mode (permissions) of a file. The permissions are unix-style and identical to those used by Python's `os.chmod` function. :param str path: path of the file to change the permissions of :param int mode: new permissions s chmod(%r, %r)N(RlRMRR+RRmR#(RNRiRRz((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytchmods   cCs_|j|}|jtd|||ft}|||_|_|jt||dS(s Change the owner (``uid``) and group (``gid``) of a file. As with Python's `os.chown` function, you must pass both arguments, so if you only want to change one, use `stat` first to retrieve the current owner and group. :param str path: path of the file to change the owner and group of :param int uid: new owner's uid :param int gid: new group id schown(%r, %r, %r)N(RlRMRR+tst_uidtst_gidRmR#(RNRituidtgidRz((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytchowns  cCs|j|}|dkr6tjtjf}n|jtd||ft}|\|_|_|jt ||dS(s Set the access and modified times of the file specified by ``path``. If ``times`` is ``None``, then the file's access and modified times are set to the current time. Otherwise, ``times`` must be a 2-tuple of numbers, of the form ``(atime, mtime)``, which is used to set the access and modified times, respectively. This bizarre API is mimicked from Python for the sake of consistency -- I apologize. :param str path: path of the file to modify :param tuple times: ``None`` or a tuple of (access time, modified time) in standard internet epoch time (seconds since 01 January 1970 GMT) s utime(%r, %r)N( RlR@ttimeRMRR+tst_atimetst_mtimeRmR#(RNRittimesRz((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytutimes  cCsR|j|}|jtd||ft}||_|jt||dS(sL Change the size of the file specified by ``path``. This usually extends or shrinks the size of the file, just like the `~file.truncate` method on Python file objects. :param str path: path of the file to modify :param size: the new size of the file :type size: int or long struncate(%r, %r)N(RlRMRR+tst_sizeRmR#(RNRitsizeRz((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyttruncates   cCs|j|}|jtd||jt|\}}|tkrVtdn|j}|dkrrdS|dkrtd|nt |j S(s Return the target of a symbolic link (shortcut). You can use `symlink` to create these. The result may be either an absolute or relative pathname. :param str path: path of the symbolic link file :return: target path, as a `str` s readlink(%r)sExpected name responseiisReadlink returned %d resultsN( RlRMRRmR$RRRpR@R5R{(RNRiRWRaRw((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytreadlinks     cCs|j|}|jtd||jt|\}}|tkrVtdn|j}|dkrtd|n|jS(s Return the normalized path (on the server) of a given path. This can be used to quickly resolve symbolic links or determine what the server is considering to be the "current folder" (by passing ``'.'`` as ``path``). :param str path: path to be normalized :return: normalized form of the given path (as a `str`) :raises IOError: if the path can't be resolved on the server s normalize(%r)sExpected name responseisRealpath returned %d results( RlRMRRmR%RRRpRr(RNRiRWRaRw((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyt normalizes    cCs{|dkrd|_dStj|j|js_ttjdtj tj|fnt |j ||_dS(s@ Change the "current directory" of this SFTP session. Since SFTP doesn't really have the concept of a current working directory, this is emulated by Paramiko. Once you use this method to set a working directory, all operations on this `.SFTPClient` object will be relative to that path. You can pass in ``None`` to stop using a current working directory. :param str path: new current working directory :raises IOError: if the requested path doesn't exist on the server .. versionadded:: 1.4 Ns%s: %s( R@RARtS_ISDIRRRterrnotENOTDIRtoststrerrorRR(RNRi((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytchdir2s   +cCs|jot|jS(s Return the "current working directory" for this SFTP session, as emulated by Paramiko. If no directory has been set with `chdir`, this method will return ``None``. .. versionadded:: 1.4 (RAR (RN((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytgetcwdHs cCsud}xhtrp|jd}|j||t|7}t|dkrQPn|dk r |||q q W|S(Nii(RotreadtwritetlenR@(RNtreadertwritert file_sizetcallbackRtdata((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyt_transfer_with_callbackSs   ic Cs|j|d8}|jt|jd|d|d|d|}WdQX|r|j|}|j|krtd|j|fqn t}|S(s Copy the contents of an open file object (``fl``) to the SFTP server as ``remotepath``. Any exception raised by operations will be passed through. The SFTP operations use pipelining for speed. :param fl: opened file or file-like object to copy :param str remotepath: the destination path on the SFTP server :param int file_size: optional size parameter passed to callback. If none is specified, size defaults to 0 :param callable callback: optional callback function (form: ``func(int, int)``) that accepts the bytes transferred so far and the total bytes to be transferred (since 1.7.4) :param bool confirm: whether to do a stat() on the file afterwards to confirm the file size (since 1.7.7) :return: an `.SFTPAttributes` object containing attributes about the given file. .. versionadded:: 1.10 twbRRRRNssize mismatch in put! %d != %d(tfilet set_pipelinedRoRRRtIOErrorR+( RNtflt remotepathRRtconfirmtfrRR4((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytputfo_s  ! c CsGtj|j}t|d }|j|||||SWdQXdS(sb Copy a local file (``localpath``) to the SFTP server as ``remotepath``. Any exception raised by operations will be passed through. This method is primarily provided as a convenience. The SFTP operations use pipelining for speed. :param str localpath: the local file to copy :param str remotepath: the destination path on the SFTP server. Note that the filename should be included. Only specifying a directory may result in an error. :param callable callback: optional callback function (form: ``func(int, int)``) that accepts the bytes transferred so far and the total bytes to be transferred :param bool confirm: whether to do a stat() on the file afterwards to confirm the file size :return: an `.SFTPAttributes` object containing attributes about the given file .. versionadded:: 1.4 .. versionchanged:: 1.7.4 ``callback`` and rich attribute return value added. .. versionchanged:: 1.7.7 ``confirm`` param added. trbN(RRRRR(RNt localpathRRRRR((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytputsc Cs`|j|j}|j|d6}|j||jd|d|d|d|SWdQXtS(s Copy a remote file (``remotepath``) from the SFTP server and write to an open file or file-like object, ``fl``. Any exception raised by operations will be passed through. This method is primarily provided as a convenience. :param object remotepath: opened file or file-like object to copy to :param str fl: the destination path on the local host or open file object :param callable callback: optional callback function (form: ``func(int, int)``) that accepts the bytes transferred so far and the total bytes to be transferred :return: the `number ` of bytes written to the opened file object .. versionadded:: 1.10 RRRRRN(RRRtprefetchRR(RNRRRRR((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytgetfos   cCskt|d}|j|||}WdQXtj|}|j|krgtd|j|fndS(s Copy a remote file (``remotepath``) from the SFTP server to the local host as ``localpath``. Any exception raised by operations will be passed through. This method is primarily provided as a convenience. :param str remotepath: the remote file to copy :param str localpath: the destination path on the local host :param callable callback: optional callback function (form: ``func(int, int)``) that accepts the bytes transferred so far and the total bytes to be transferred .. versionadded:: 1.4 .. versionchanged:: 1.7.4 Added the ``callback`` param RNssize mismatch in get! %d != %d(RRRRRR(RNRRRRRR4((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pytgets cGs(|jtd||}|j|S(N(R|RER@t_read_response(RNRWtargR((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyRmscGs#|jjzt}|j|jx|D]}t|trU|j|q0t|trt|j|q0t|t t fr|j |q0t|t r|j |q0td|t|fq0W|j}||j|<|jd7_Wd|jjX|j|||S(Nsunknown type for %r type %ri(R?tacquireRtadd_intR<R[R t add_int64tintR R t add_stringR+t_packt ExceptionRERDtreleaset _send_packet(RNtfileobjRWRRatitemR((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyR|s(      cCsJxCtrEy|j\}}Wn)tk rJ}tdt|nXt|}|j}|jjzW||j kr|j t d|f|dkrPnwn|j |}|j |=Wd|jj X||kr |tkr|j|n||fS|tdk r2|j|||n|dkrPqqWdS(NsServer connection dropped: %ssUnexpected response #%d(NN(RoR}RLR,tstrRRpR?RRDRMRR@RR&R~REt_async_response(RNtwaitforRWRteRaRR((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyRs4          cCs4x-||jjkr/|j|jqWdS(N(RDtvaluesRt_check_exception(RNR((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyt_finish_responsess cCs|j}|j}|tkr(dS|tkrCt|nN|tkrdttj|n-|t krttj |n t|dS(sU Raises EOFError or IOError on error status; otherwise does nothing. N( RpRrR'R(RLR)RRtENOENTR*tEACCES(RNRatcodettext((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyR~s      cCskt|}|jdkr|St|rB|dd!tkrB|S|jtkr\|j|S|jt|S(sr Return an adjusted path if we're emulating a "current working directory" for the server. iiN(RRAR@Rtb_slash(RNRi((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyRl-s  N(,t__name__t __module__t__doc__R8t classmethodR@RYRMRdReRkRgRRRRtunlinkRRRRRRRRRRRRRRRRRoRRRRRmR|RRR~Rl(((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyR7>sN ! *A6             (     !  tSFTPcBseZdZRS(sA An alias for `.SFTPClient` for backwards compatability. (RRR(((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyR=s(DtbinasciiRRRRR=RRBtparamikoRtparamiko.channelRtparamiko.messageRtparamiko.commonRRRtparamiko.py3compatRRR R R R t paramiko.sftpR RRRRRRRRRRRRRRRRRRR R!R"R#R$R%R&R'R(R)R*tparamiko.sftp_attrR+tparamiko.ssh_exceptionR,tparamiko.sftp_fileR-t paramiko.utilR.R5RR7R(((s8/usr/lib/python2.7/site-packages/paramiko/sftp_client.pyts.      .