[ @sdZddlZddlZddlZddlZddlmZddgZdZdZdZ Gd d d e Z Gd d d e Z Gd dde Z Gddde ZGddde Ze eefZdZdZGdddZyddlZWnek r*dZYnBXejZGdddeZejde eeejfZdaddZdaddZ ddZ!ddZ"d d!Z#d"d#d$d%Z$Gd&ddZ%d'd(Z&e'd)kre&ndS)*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_TIMEOUTFTPNetrci c@seZdZdS)ErrorN)__name__ __module__ __qualname__r r /usr/lib/python3.4/ftplib.pyr:s rc@seZdZdS) error_replyN)rr r r r r r r ;s r c@seZdZdS) error_tempN)rr r r r r r r<s rc@seZdZdS) error_permN)rr r r r r r r=s rc@seZdZdS) error_protoN)rr r r r r r r>s rz s c@seZdZdZdZdZeZeZ dZ dZ dZ dZ dZddddedddZd d Zd d Zddd[dddZddZddZeZddZddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Z d(d)Z!d*d+Z"d,d-Z#d.d/Z$d0d1Z%dd2d3Z&dd4d5Z'dddd6d7Z(d8dd9d:Z)dd;d<Z*d8ddd=d>Z+dd?d@Z,dAdBZ-dCdDZ.dEdFZ/dgdGdHZ0dIdJZ1dKdLZ2dMdNZ3dOdPZ4dQdRZ5dSdTZ6dUdVZ7dWdXZ8dYdZZ9dS)\rayAn 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-1cCsH||_||_|rD|j||rD|j|||qDndS)N)source_addresstimeoutconnectlogin)selfhostuserpasswdacctrrr r r __init__qs    z FTP.__init__cCs|S)Nr )rr r r __enter__zsz FTP.__enter__cGsc|jdk r_z-y|jWnttfk r:YnXWd|jdk r[|jnXndS)N)sockquitOSErrorEOFErrorclose)rargsr r r __exit__~s z FTP.__exit__icCs|dkr||_n|dkr0||_n|dkrH||_n|dk r`||_ntj|j|jf|jd|j|_|jj|_|jj dd|j |_ |j |_ |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. rriNrrencodingi)rportrrsocketcreate_connectionrZfamilyafmakefiler%filegetrespwelcome)rrr&rrr r r rs        z FTP.connectcCs,|jr%td|j|jn|jS)z`Get the welcome message from the server. (this is read and squirreled away by connect())z *welcome*) debuggingprintsanitizer-)rr r r getwelcomes zFTP.getwelcomecCs ||_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)r.)rlevelr r r set_debuglevelszFTP.set_debuglevelcCs ||_dS)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)rvalr r r set_pasvsz FTP.set_pasvcCsb|dddkrXt|jd}|ddd|d||d}nt|S)Npass PASS z *>r8r9)lenrstriprepr)rsir r r r0s-z FTP.sanitizecCsR|t}|jdkr2td|j|n|jj|j|jdS)Nrz*put*)CRLFr.r/r0rsendallencoder%)rliner r r putlines z FTP.putlinecCs3|jr"td|j|n|j|dS)Nz*cmd*)r.r/r0rD)rrCr r r putcmds z FTP.putcmdcCs|jj|jd}t||jkrDtd|jn|jdkrltd|j|n|s{tn|ddt kr|dd}n)|ddt kr|dd}n|S) Nrzgot more than %d bytesz*get*rGrH) r+readlinemaxliner;rr.r/r0r r@)rrCr r r getlines z FTP.getlinecCs|j}|dddkr|dd}xQ|j}|d|}|dd|kr5|dddkr5Pq5q5Wn|S)N- )rK)rrCcodeZnextliner r r getmultilines   zFTP.getmultilinecCs|j}|jr.td|j|n|dd|_|dd}|d kra|S|dkr|t|n|dkrt|nt|dS) Nz*resp*rLr12345>rTrRrS)rQr.r/r0Zlastresprrr)rrespcr r r r,s     z FTP.getrespcCs5|j}|dddkr1t|n|S)z%Expect a response beginning with '2'.NrrS)r,r )rrWr r r voidresps z FTP.voidrespcCszdt}|jdkr2td|j|n|jj|t|j}|ddd krvt|n|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.sABORrz *put urgent*NrL426225226>r[r\rZ) B_CRLFr.r/r0rrAMSG_OOBrQr)rrCrWr r r aborts  z FTP.abortcCs|j||jS)z'Send a command and return the response.)rEr,)rcmdr r r sendcmd s z FTP.sendcmdcCs|j||jS)z8Send a command and expect a response beginning with '2'.)rErY)rr`r r r voidcmds z FTP.voidcmdcCsY|jd}t|dt|dg}||}ddj|}|j|S)zUSend a PORT command with the current host and the given port number. .zPORT ,)splitr=joinrb)rrr&ZhbytesZpbytesbytesr`r r r sendports   z FTP.sendportcCsd}|jtjkr!d}n|jtjkr<d}n|dkrWtdndt||t|dg}ddj|}|j|S)zDSend a EPRT command with the current host and the given port number.rrrFzunsupported address familyrzEPRT |)r)r'AF_INETZAF_INET6rr=rgrb)rrr&r)Zfieldsr`r r r sendeprt!s   !z FTP.sendeprtc Csd}d}xtjdd|jtjdtjD]}|\}}}}}y&tj|||}|j|WnGtk r} z'| }|r|jnd}w4WYdd} ~ XnXPq4W|dkr|dk r|qtdn|jd|j d} |j j d} |jtj krK|j | | } n|j | | } |jtk r|j|jn|S)z3Create a new socket and send a PORT command for it.Nrz!getaddrinfo returns an empty listr)r'Z getaddrinfor)Z SOCK_STREAMZ AI_PASSIVEZbindrr!ZlistenZ getsocknamerrkrirlrr settimeout) rerrrZresr)ZsocktypeprotoZ canonnameZsa_r&rrWr r r makeport.s6.     z FTP.makeportcCsa|jtjkr0t|jd\}}n't|jd|jj\}}||fS)NPASVZEPSV)r)r'rkparse227raparse229rZ getpeername)rrr&r r r makepasvNs'z FTP.makepasvc Csd}|jr|j\}}tj||f|jd|j}yq|dk rh|jd|n|j|}|ddkr|j}n|ddkrt|nWq|j YqXn|j }|dk r|jd|n|j|}|ddkr.|j}n|ddkrMt|n|j \}} |jt k r|j |jnWdQX|dddkrt|}n||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. NrzREST %srrSrRrL150)r4rur'r(rrrar,r r!rqZacceptrrmparse150) rr`restsizerr&connrWrZsockaddrr r r ntransfercmdUs<      zFTP.ntransfercmdcCs|j||dS)z0Like ntransfercmd() but returns only the socket.r)r{)rr`rxr r r transfercmdszFTP.transfercmdcCs|sd}n|sd}n|s-d}n|dkrR|d krR|d}n|jd|}|ddkr|jd|}n|ddkr|jd |}n|dd krt|n|S) zLogin, default anonymous.Z anonymousrrNz anonymous@zUSER rrTzPASS zACCT rS>rrN)rar )rrrrrWr r r rs     z FTP.logini c Cs|jd|j||Y}x'|j|}|s>Pn||q%Wtdk rtt|trt|jnWdQX|jS)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. zTYPE IN)rbr|Zrecv _SSLSocket isinstanceunwraprY)rr`callback blocksizerxrzdatar r r retrbinarys zFTP.retrbinarycCsb|dkrt}n|jd}|j|#}|jdd|j}x|j|jd}t||jkrtd|jn|j dkrt dt |n|sPn|d dt kr|dd }n)|d dd kr|dd }n||qTWt dk rLt|t rL|jnWdQXWdQX|jS)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. NzTYPE Ar$r%rzgot more than %d bytesrFz*retr*rOrGrGrHrH) print_linerar|r*r%rIrJr;rr.r/r=r@r}r~rrY)rr`rrWrzfprCr r r retrliness*  z FTP.retrlinesc Cs|jd|j||o}x=|j|}|s>Pn|j||r%||q%q%Wtdk rt|tr|jnWdQX|jS)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. zTYPE IN)rbr|readrAr}r~rrY)rr`rrrrxrzbufr r r storbinarys  zFTP.storbinaryc Cs|jd|j|}x|j|jd}t||jkrctd|jn|smPn|ddtkr|dtkr|dd}n|t}n|j||r"||q"q"Wtdk rt |tr|j nWdQX|j 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. zTYPE Arzgot more than %d bytesrFNrGrHrH) rbr|rIrJr;rr]rAr}r~rrY)rr`rrrzrr r r storliness$   z FTP.storlinescCsd|}|j|S)zSend new account name.zACCT )rb)rpasswordr`r r r r#s zFTP.acctcGsBd}x|D]}|d|}q Wg}|j||j|S)zBReturn a list of files in a given directory (default the current).ZNLST )rappend)rr"r`argZfilesr r r nlst(s  zFTP.nlstcGsd}d}|ddrVt|dtdkrV|dd|d }}nx%|D]}|r]|d|}q]q]W|j||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.)ZLISTNrrrrHrHrHrH)typer)rr"r`funcrr r r dir1s, zFTP.dirc cs|r'|jddj|dn|r:d|}nd}g}|j||jx|D]}|jtjd\}}}i} xI|dd jdD].} | jd\} }} | | | jrr)rar )rfilenamerWr r r deletecsz FTP.deletecCs|dkrky|jdSWqtk rg}z(|jddddkrUnWYdd}~XqXn|dkrd}nd |}|j|S) zChange to a directory.z..ZCDUPrNrL500rrczCWD )rbrr")rdirnamemsgr`r r r cwdks    zFTP.cwdcCsM|jd|}|dddkrI|ddj}t|SdS)zRetrieve the size of a file.zSIZE NrLZ213)rastripint)rrrWr>r r r ryxszFTP.sizecCs0|jd|}|jds&dSt|S)z+Make a directory, return its full pathname.zMKD 257r)rb startswithparse257)rrrWr r r mkdszFTP.mkdcCs|jd|S)zRemove a directory.zRMD )rb)rrr r r rmdszFTP.rmdcCs,|jd}|jds"dSt|S)z!Return current working directory.ZPWDrr)rbrr)rrWr r r pwdszFTP.pwdcCs|jd}|j|S)zQuit, and close the connection.ZQUIT)rbr!)rrWr r r rs zFTP.quitcCsR|jdk r|jjn|jdk r>|jjnd|_|_dS)z8Close the connection without assuming anything about it.N)r+r!r)rr r r r!s z FTP.closei):rr r __doc__r.rFTP_PORTr&MAXLINErJrr+r-r4r%rrrr#rr1r3debugr6r0rDrErKrQr,rYr_rarbrirlrqrur{r|rrrrrrrrrrrrryrrrrr!r r r r rKsj                  7#       c @seZdZdZejZdddddddeddd ZddddddZ 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 r'tdn|dk rN|dk rNtdn||_||_|dkrtj|jd|d|}n||_d|_tj ||||||| dS)Nz4context and keyfile arguments are mutually exclusivez5context and certfile arguments are mutually exclusivecertfilekeyfileF) ValueErrorrrsslZ_create_stdlib_context ssl_versioncontext_prot_prr) rrrrrrrrrrr r r rs      zFTP_TLS.__init__TcCs?|r)t|jtj r)|jntj||||S)N)r~rr SSLSocketauthrr)rrrrZsecurer r r rs z FTP_TLS.logincCst|jtjr$tdn|jtjkrH|jd}n|jd}|jj |jd|j |_|jj ddd|j |_ |S)z2Set up secure control connection by using TLS/SSL.zAlready using TLSzAUTH TLSzAUTH SSLserver_hostnamemoder$r%)r~rrrrrPROTOCOL_SSLv23rbr wrap_socketrr*r%r+)rrWr r r rs!z FTP_TLS.authcCsIt|jtjs$tdn|jd}|jj|_|S)z/Switch back to a clear-text control connection.z not using TLSZCCC)r~rrrrrbr)rrWr r r cccs z FTP_TLS.ccccCs)|jd|jd}d|_|S)zSet up secure data connection.zPBSZ 0zPROT PT)rbr)rrWr r r prot_ps  zFTP_TLS.prot_pcCs|jd}d|_|S)z"Set up clear text data connection.zPROT CF)rbr)rrWr r r prot_c s zFTP_TLS.prot_ccCsLtj|||\}}|jrB|jj|d|j}n||fS)Nr)rr{rrrr)rr`rxrzryr r r r{s  zFTP_TLS.ntransfercmdcCsOdt}|jj||j}|dddkrKt|n|S)NsABORrLrZr[r\>225226426)r]rrArQr)rrCrWr r r r_s   z FTP_TLS.abort)rr r rrrrrrrrrrrr{r_r r r r rs     rcCs|dddkr%t|ntdkr\ddl}|jd|j|jBantj|}|sudSt|jdS)zParse the '150' response for a RETR request. Returns the expected transfer size or None; size is not guaranteed to be present in the 150 message. NrLrvrz150 .* \((\d+) bytes\)r) r _150_rerecompile IGNORECASEASCIImatchrgroup)rWrmr r r rw)s  rwcCs|dddkr%t|ntdkrUddl}|jd|jantj|}|syt|n|j}dj|dd}t |dd>t |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.NrLZ227rz#(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)rcrMr7) r _227_rerrrsearchrgroupsrgr)rWrrZnumbersrr&r r r rs=s   "rscCs|dddkr%t|n|jd}|dkrOt|n|jd|d}|dkrt|n||d||dkrt|n||d|j||d}t|dkrt|n|d}t|d}||fS) zParse the '229' response for a EPSV request. Raises error_proto if it does not contain '(|||port|)' Return ('host.addr.as.numbers', port#) tuple.NrLZ229(r)rr7)r findrrfr;r)rWZpeerleftrightpartsrr&r r r rtQs   % rtcCs|dddkr%t|n|dddkr?dSd}d}t|}xg||kr||}|d}|dkr||ks||dkrPn|d}n||}qZW|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.NrLrr7z "rr")r r;)rWrr?nrXr r r rgs      rcCst|dS)z+Default retrlines callback to print a line.N)r/)rCr r r r~srrIc Cs|s|}nd|}|j||j|t|jd\}}|j|||jd|}|ddd krtn|jd|}|ddd krtn|j|jdS) z+Copy file from one FTP-instance to another.zTYPE rrzSTOR NrL125rvzRETR >r150>rr)rbrsrarirrY) sourceZ sourcenametargetZ targetnamerZ sourcehostZ sourceportZtreplyZsreplyr r r ftpcps       rc@sgeZdZdZdZdZdZdddZddZddZ d d Z d d Z dS) rzClass to parse & provide access to 'netrc' format files. See the netrc(4) man page for information on the file format. WARNING: This class is obsolete -- use module netrc instead. NcCstjdtd|dkr\dtjkrMtjjtjdd}q\tdni|_i|_ t |d}d}xf|j }|sPn|r|j r|j |qn"|rt||j |sP     [   x      m 7