B /g^c@sVdZddlZddlZddlmZdddddd gZd Zd Zd ZGd ddeZ Gddde Z Gddde Z Gddde Z Gddde Z e eefZdZdZGdddZy ddlZWnek rdZYn0XejZGdddeZede eeejfZdaddZdaddZddZddZ d d!Z!d)d$d%Z"d&d'Z#e$d(krRe#dS)*aSAn FTP client class and some helper functions. Based on RFC 959: File Transfer Protocol (FTP), by J. Postel and J. Reynolds Example: >>> from ftplib import FTP >>> ftp = FTP('ftp.python.org') # connect to host, default port >>> ftp.login() # default, i.e.: user anonymous, passwd anonymous@ '230 Guest login ok, access restrictions apply.' >>> ftp.retrlines('LIST') # list directory contents total 9 drwxr-xr-x 8 root wheel 1024 Jan 3 1994 . drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .. drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr -rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg '226 Transfer complete.' >>> ftp.quit() '221 Goodbye.' >>> A nice test that reveals some of the network dialogue would be: python ftplib.py -d localhost -l -p -l N)_GLOBAL_DEFAULT_TIMEOUTFTP error_reply error_temp error_perm error_proto all_errorsi c@ eZdZdS)ErrorN__name__ __module__ __qualname__rr/usr/lib64/python3.7/ftplib.pyr 9r c@r )rNr rrrrr:rc@r )rNr rrrrr;rc@r )rNr rrrrr<rc@r )rNr rrrrr=r s c@seZdZdZdZdZeZeZ dZ dZ dZ dZ dZddddedfddZd d Zd d Zd[ddZddZddZeZddZddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Z d(d)Z!d*d+Z"d,d-Z#d.d/Z$d0d1Z%d\d2d3Z&d]d4d5Z'd^d6d7Z(d_d9d:Z)d`d;d<Z*dad=d>Z+dbd?d@Z,dAdBZ-dCdDZ.dEdFZ/dgfdGdHZ0dIdJZ1dKdLZ2dMdNZ3dOdPZ4dQdRZ5dSdTZ6dUdVZ7dWdXZ8dYdZZ9dS)crayAn FTP client class. To create a connection, call the class using these arguments: host, user, passwd, acct, timeout The first four arguments are all strings, and have default value ''. timeout must be numeric and defaults to None if not passed, meaning that no timeout will be set on any ftp socket(s) If a timeout is passed, then this is now the default timeout for all ftp socket operations for this instance. Then use self.connect() with optional host and port argument. To download a file, use ftp.retrlines('RETR ' + filename), or ftp.retrbinary() with slightly different arguments. To upload a file, use ftp.storlines() or ftp.storbinary(), which have an open file as argument (see their definitions below for details). The download/upload functions first issue appropriate TYPE and PORT or PASV commands. rNrzlatin-1cCs0||_||_|r,|||r,||||dSN)source_addresstimeoutconnectlogin)selfhostuserpasswdacctrrrrr__init__ps  z FTP.__init__cCs|Srrrrrr __enter__ysz FTP.__enter__c GsN|jdk rJz*y |Wnttfk r0YnXWd|jdk rH|XdSr)sockquitOSErrorEOFErrorclose)rargsrrr__exit__}s    z FTP.__exit__cCs|dkr||_|dkr||_|dkr*||_|dk r8||_tj|j|jf|j|jd|_|jj|_|jj d|j d|_ | |_ |j S)awConnect to host. Arguments are: - host: hostname to connect to (string, default previous host) - port: port to connect to (integer, default previous port) - timeout: the timeout to set against the ftp socket(s) - source_address: a 2-tuple (host, port) for the socket to bind to as its source address before connecting. rrr)Nrrencoding)rportrrsocketcreate_connectionr"Zfamilyafmakefiler-filegetrespwelcome)rrr.rrrrrrs   z FTP.connectcCs|jrtd||j|jS)z`Get the welcome message from the server. (this is read and squirreled away by connect())z *welcome*) debuggingprintsanitizer5r rrr getwelcomeszFTP.getwelcomecC ||_dS)zSet the debugging level. The required argument level means: 0: no debugging output (default) 1: print commands and responses but not body text etc. 2: also print raw lines read and sent before stripping CR/LFN)r6)rZlevelrrrset_debuglevelszFTP.set_debuglevelcCr:)zUse passive or active mode for data transfers. With a false argument, use the normal PORT mode, With a true argument, use the PASV command.N) passiveserver)rZvalrrrset_pasvsz FTP.set_pasvcCsJ|dddkrBt|d}|ddd|d||d}t|S)N>PASS zpass rZ*)lenrstriprepr)rsirrrr8s$z FTP.sanitizecCsRd|ksd|krtd|t}|jdkr:td|||j||jdS)Nz  z4an illegal newline character should not be containedrz*put*) ValueErrorCRLFr6r7r8r"sendallZencoder-rlinerrrputlines  z FTP.putlinecCs$|jrtd||||dS)Nz*cmd*)r6r7r8rKrIrrrputcmdsz FTP.putcmdcCs|j|jd}t||jkr.td|j|jdkrHtd|||sPt|ddt krn|dd}n|ddt kr|dd}|S)Nrgot more than %d bytesz*get*) r3readlinemaxliner@r r6r7r8r%rGrIrrrgetlines  z FTP.getlinecCsd|}|dddkr`|dd}x:|}|d|}|dd|kr&|dddkr&Pq&W|S)N-rE)rR)rrJZcodeZnextlinerrr getmultilines  zFTP.getmultilinecCsp|}|jrtd|||dd|_|dd}|dkrD|S|dkrTt||dkrdt|t|dS)Nz*resp*rSr>123Z4Z5)rVr6r7r8Zlastresprrr)rrespcrrrr4s z FTP.getrespcCs$|}|dddkr t||S)z%Expect a response beginning with '2'.NrrX)r4rrrZrrrvoidrespsz FTP.voidrespcCsTdt}|jdkr"td|||j|t|}|dddkrPt||S)zAbort a file transfer. Uses out-of-band data. This does not follow the procedure from the RFC to send Telnet IP and Synch; that doesn't seem to work with the servers I've tried. Instead, just send the ABOR command as OOB data.ABORrz *put urgent*NrSZ225Z426Z226) B_CRLFr6r7r8r"rHMSG_OOBrVrrrJrZrrraborts z FTP.abortcC|||S)z'Send a command and return the response.)rLr4rcmdrrrsendcmd z FTP.sendcmdcCrd)z8Send a command and expect a response beginning with '2'.)rLr]rerrrvoidcmdrhz FTP.voidcmdcCsB|d}t|dt|dg}||}dd|}||S)zUSend a PORT command with the current host and the given port number. .izPORT z,)splitrBjoinri)rrr.ZhbytesZpbytesZbytesrfrrrsendports  z FTP.sendportcCsbd}|jtjkrd}|jtjkr$d}|dkr4tddt||t|dg}dd|}||S)zESend an EPRT command with the current host and the given port number.rrzunsupported address familyrzEPRT z|)r1r/AF_INETZAF_INET6rrBrlri)rrr.r1Zfieldsrfrrrsendeprt"s  z FTP.sendeprtc Csd}d}xtdd|jtjdtjD]j}|\}}}}}yt|||}||Wn8tk r} z| }|rt|d}w$Wdd} ~ XYnXPq$W|dkr|dk r|ntd|d| d} |j d} |jtj kr| | | } n | | | } |jtk r||j|S)z3Create a new socket and send a PORT command for it.Nrz!getaddrinfo returns an empty listr)r/Z getaddrinfor1Z SOCK_STREAMZ AI_PASSIVEZbindr$r&ZlistenZ getsocknamer"rormrprr settimeout) rZerrr"Zresr1ZsocktypeZprotoZ canonnameZsa_r.rrZrrrmakeport/s6       z FTP.makeportcCsB|jtjkr t|d\}}nt|d|j\}}||fS)NPASVZEPSV)r1r/roparse227rgparse229r"Z getpeername)rrr.rrrmakepasvOs z FTP.makepasvc Cs6d}|jr|\}}tj||f|j|jd}yL|dk rF|d|||}|ddkrd|}|ddkrxt|Wn| YnXn| r}|dk r|d|||}|ddkr|}|ddkrt|| \}} |jt k r | |jWdQRX|dddkr.t|}||fS) aInitiate a transfer over the data connection. If the transfer is active, send a port command and the transfer command, and accept the connection. If the server is passive, send a pasv command, connect to it, and start the transfer command. Either way, return the socket for the connection and the expected size of the transfer. The expected size may be None if it could not be determined. Optional `rest' argument can be a string that is sent as the argument to a REST command. This is essentially a server marker used to tell the server to skip over any data up to the given marker. Nr*zREST %srrXrWrS150)r<rwr/r0rrrgr4rr&rsZacceptrrqparse150) rrfrestsizerr.connrZr"Zsockaddrrrr ntransfercmdVs<             zFTP.ntransfercmdcCs|||dS)z0Like ntransfercmd() but returns only the socket.r)r})rrfrzrrr transfercmdzFTP.transfercmdcCs|sd}|sd}|sd}|dkr0|dkr0|d}|d|}|ddkrX|d|}|ddkrr|d |}|dd krt||S) zLogin, default anonymous.Z anonymousr>rrUz anonymous@zUSER rrYr?ACCT rXrgr)rrrrrZrrrrs    z FTP.loginr c Csb|d|||>}x||}|s*P||qWtdk rPt|trP|WdQRX|S)aRetrieve data in binary mode. A new port is created for you. Args: cmd: A RETR command. callback: A single parameter callable to be called on each block of data read. blocksize: The maximum number of bytes to read from the socket at one time. [default: 8192] rest: Passed to transfercmd(). [default: None] Returns: The response code. TYPE IN)rir~Zrecv _SSLSocket isinstanceunwrapr])rrfcallback blocksizerzr|Zdatarrr retrbinarys   zFTP.retrbinaryc Cs|dkr t}|d}||}|jd|jd}x||jd}t||jkrbtd|j|j dkrzt dt ||sP|d dt kr|dd }n|d dd kr|dd }||q6Wt dk rt|t r|WdQRXWdQRX|S) ahRetrieve data in line mode. A new port is created for you. Args: cmd: A RETR, LIST, or NLST command. callback: An optional single parameter callable that is called for each line with the trailing CRLF stripped. [default: print_line()] Returns: The response code. NTYPE Ar+r,rrMrnz*retr*rNrOrE) print_linergr~r2r-rPrQr@r r6r7rBrGrrrr])rrfrrZr|fprJrrr retrliness*      z FTP.retrlinesc Csp|d|||L}x*||}|s*P|||r||qWtdk r^t|tr^|WdQRX|S)a9Store a file in binary mode. A new port is created for you. Args: cmd: A STOR command. fp: A file-like object with a read(num_bytes) method. blocksize: The maximum data size to read from fp and send over the connection at once. [default: 8192] callback: An optional single parameter callable that is called on each block of data after it is sent. [default: None] rest: Passed to transfercmd(). [default: None] Returns: The response code. rN)rir~ZreadrHrrrr])rrfrrrrzr|bufrrr storbinarys    zFTP.storbinaryc Cs|d||}x|||jd}t||jkrDtd|j|sJP|ddtkrz|dtkrr|dd}|t}|||r||qWtdk rt |tr| WdQRX| S)ahStore a file in line mode. A new port is created for you. Args: cmd: A STOR command. fp: A file-like object with a readline() method. callback: An optional single parameter callable that is called on each line after it is sent. [default: None] Returns: The response code. rrrMrNNrO) rir~rPrQr@r r`rHrrrr])rrfrrr|rrrr storliness$     z FTP.storlinescCsd|}||S)zSend new account name.rri)rZpasswordrfrrrr$szFTP.acctcGs4d}x|D]}|d|}q Wg}|||j|S)zBReturn a list of files in a given directory (default the current).ZNLST )rappend)rr'rfargZfilesrrrnlst)s  zFTP.nlstcGsld}d}|ddr>t|dtdkr>|dd|d}}x|D]}|rD|d|}qDW|||dS)aList a directory in long form. By default list current directory to stdout. Optional last argument is callback function; all non-empty arguments before it are concatenated to the LIST command. (This *should* only be used for a pathname.)ZLISTNrOrr)typer)rr'rfZfuncrrrrdir2s  zFTP.dirc cs|r|dd|d|r*d|}nd}g}|||jxh|D]`}|td\}}}i} x6|dddD] } | d\} }} | | | <qxW|| fVqFWdS) a<List a directory in a standardized format by using MLSD command (RFC-3659). If path is omitted the current directory is assumed. "facts" is a list of strings representing the type of information desired (e.g. ["type", "size", "perm"]). Return a generator object yielding a tuple of two elements for every file found in path. First element is the file name, the second one is a dictionary including a variable number of "facts" depending on the server and whether "facts" argument has been provided. z OPTS MLST z;zMLSD %sZMLSDrNrOz=) rgrlrrrArGZ partitionrkZlower) rZpathZfactsrfZlinesrJZ facts_foundrrZnameZentryZfactZkeyZvaluerrrmlsdAs   zFTP.mlsdcCs0|d|}|ddkr"t||d|S)zRename a file.zRNFR rrYzRNTO )rgrri)rZfromnameZtonamerZrrrrename]s z FTP.renamecCs.|d|}|dddkr"|St|dS)zDelete a file.zDELE NrS>Z250Z200r)rfilenamerZrrrdeletedsz FTP.deletec Csn|dkrPy |dStk rL}z|jddddkr<Wdd}~XYq\Xn |dkr\d}d |}||S) zChange to a directory.z..ZCDUPrNrSZ500rrjzCWD )rirr')rdirnameZmsgrfrrrcwdls zFTP.cwdcCs:|d|}|dddkr6|dd}t|SdS)zRetrieve the size of a file.zSIZE NrSZ213)rgZstripint)rrrZrCrrrr{yszFTP.sizecCs$|d|}|dsdSt|S)z+Make a directory, return its full pathname.zMKD 257rriZ startswithparse257)rrrZrrrmkds zFTP.mkdcCs|d|S)zRemove a directory.zRMD r)rrrrrrmdrzFTP.rmdcCs |d}|dsdSt|S)z!Return current working directory.ZPWDrrrr\rrrpwds  zFTP.pwdcCs|d}||S)zQuit, and close the connection.ZQUIT)rir&r\rrrr#s zFTP.quitcCsDz |j}d|_|dk r|Wd|j}d|_|dk r>|XdS)z8Close the connection without assuming anything about it.N)r3r&r")rr3r"rrrr&s z FTP.close)rrr)Nrr)rrr)r Nr)r NNr):r rr__doc__r6rFTP_PORTr.MAXLINErQr"r3r5r<r-rrr!r(rr9r;Zdebugr=r8rKrLrRrVr4r]rcrgrirmrprsrwr}r~rrrrrrrrrrrrr{rrrr#r&rrrrrJsj      7    #      c @sneZdZdZejZdddddddedf ddZdddZ d d Z d d Z d dZ ddZ dddZddZdS)FTP_TLSaA FTP subclass which adds TLS support to FTP as described in RFC-4217. Connect as usual to port 21 implicitly securing the FTP control connection before authenticating. Securing the data connection requires user to explicitly ask for it by calling prot_p() method. Usage example: >>> from ftplib import FTP_TLS >>> ftps = FTP_TLS('ftp.python.org') >>> ftps.login() # login anonymously previously securing control channel '230 Guest login ok, access restrictions apply.' >>> ftps.prot_p() # switch to secure data connection '200 Protection level set to P' >>> ftps.retrlines('LIST') # list directory content securely total 9 drwxr-xr-x 8 root wheel 1024 Jan 3 1994 . drwxr-xr-x 8 root wheel 1024 Jan 3 1994 .. drwxr-xr-x 2 root wheel 1024 Jan 3 1994 bin drwxr-xr-x 2 root wheel 1024 Jan 3 1994 etc d-wxrwxr-x 2 ftp wheel 1024 Sep 5 13:43 incoming drwxr-xr-x 2 root wheel 1024 Nov 17 1993 lib drwxr-xr-x 6 1094 wheel 1024 Sep 13 19:07 pub drwxr-xr-x 3 root wheel 1024 Jan 3 1994 usr -rw-r--r-- 1 root root 312 Aug 1 1994 welcome.msg '226 Transfer complete.' >>> ftps.quit() '221 Goodbye.' >>> rNc Cs|dk r|dk rtd|dk r0|dk r0td|dk s@|dk rVddl} | dtd||_||_|dkr|tj|j||d}||_ d|_ t ||||||| dS)Nz4context and keyfile arguments are mutually exclusivez5context and certfile arguments are mutually exclusiverzAkeyfile and certfile are deprecated, use a custom context insteadrn)certfilekeyfileF) rFwarningsZwarnZDeprecationWarningrrsslZ_create_stdlib_context ssl_versioncontext_prot_prr) rrrrrrrrrrrrrrrs"zFTP_TLS.__init__TcCs*|rt|jtjs|t||||Sr)rr"r SSLSocketauthrr)rrrrZsecurerrrrsz FTP_TLS.logincCsft|jtjrtd|jtjkr.|d}n |d}|jj |j|j d|_|jj d|j d|_ |S)z2Set up secure control connection by using TLS/SSL.zAlready using TLSzAUTH TLSzAUTH SSLZserver_hostnamer+)Zmoder-)rr"rrrFrZ PROTOCOL_TLSrir wrap_socketrr2r-r3r\rrrrs     z FTP_TLS.authcCs0t|jtjstd|d}|j|_|S)z/Switch back to a clear-text control connection.z not using TLSZCCC)rr"rrrFrirr\rrrcccs   z FTP_TLS.ccccCs|d|d}d|_|S)zSet up secure data connection.zPBSZ 0zPROT PTrirr\rrrprot_ps  zFTP_TLS.prot_pcCs|d}d|_|S)z"Set up clear text data connection.zPROT CFrr\rrrprot_cs zFTP_TLS.prot_ccCs2t|||\}}|jr*|jj||jd}||fS)Nr)rr}rrrr)rrfrzr|r{rrrr}s  zFTP_TLS.ntransfercmdcCs8dt}|j||}|dddkr4t||S)Nr^rSr_)r`r"rHrVrrbrrrrc$s  z FTP_TLS.abort)rrrTr)r rrrrZPROTOCOL_TLS_CLIENTrrrrrrrrr}rcrrrrrs     rcCs\|dddkrt|tdkrt |d }||fS) zParse the '227' response for a PASV request. Raises error_proto if it does not contain '(h1,h2,h3,h4,p1,p2)' Return ('host.addr.as.numbers', port#) tuple.NrSZ227rz#(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)rjrTir>) r_227_rerrrZsearchrZgroupsrlr)rZrrZnumbersrr.rrrruGs rucCs|dddkrt||d}|dkr2t||d|d}|dkrRt|||d||dkrrt|||d|||d}t|dkrt||d}t|d}||fS) zParse the '229' response for an EPSV request. Raises error_proto if it does not contain '(|||port|)' Return ('host.addr.as.numbers', port#) tuple.NrSZ229z(rz)rr>)rZfindrrkr@r)rZZpeerZleftZrightZpartsrr.rrrrv[s    rvcCs|dddkrt||dddkr,dSd}d}t|}xJ||kr||}|d}|dkr|||ksr||dkrtP|d}||}q>W|S) zParse the '257' response for a MKD or PWD request. This is a response to a MKD or PWD request: a directory name. Returns the directoryname in the 257 reply.NrSrr>z "rrz")rr@)rZrrDZnr[rrrrqs   rcCs t|dS)z+Default retrlines callback to print a line.N)r7)rJrrrrrrrIc Cs|s|}d|}||||t|d\}}||||d|}|dddkrdt|d|}|dddkrt||dS)z+Copy file from one FTP-instance to another.zTYPE rtzSTOR NrS>rxZ125RETR )rirurgrmrr]) ZsourceZ sourcenameZtargetZ targetnamerZ sourcehostZ sourceportZtreplyZsreplyrrrftpcps   rc Csttjdkr"ttjtdddl}d}d}x"tjddkrT|d}tjd=q4Wtjddddkrtjddd}tjd=tjd}t|}| |d}}}y||}Wn(t k r|dk rtj dYn:Xy| |\}}}Wn"tk rtj d YnX||||xtjddD]} | ddd krf|| ddnt| dddkrd } | ddr| d | dd} || } n0| d kr||j n|d| tjj dqsP    d  |  9