1 FTP (File Transfer Protocol) workflow
1 clients connect to an FTP server on a remote host
2 Client input user name and password (or ' anomymous ' and e-mail address)
3 Client for various file transfer and information query operations
4 client exits directly from remote FTP server, ends transmission
FTP two modes: active and passive, only the active mode server uses the data port, number 20th. In passive mode, the server is just a high number of client-side random port numbers, and the client must actively establish the connection, number 21st.
2 python and FTP
Import the Ftplib module and instantiate a ftplib. FTP class object, all FTP operations (such as login, transfer files and logoff) are to be completed by this object
Ftplib. FTP class method, only introduce a few common
Login (user= ' anonymous ', passwd= ", act=") #登录服务器, all parameters are optional
PWD #获取当前目录
CWD (path) #把当前工作目录设置path所示的路径 (e.g. path=/ftp/byq/example)
Dir ([path[,... [, CB]]) # Displays the contents of the path directory, optional parameter CB is a callback function, passed to the Retrlines () method
Retrbinary (cmd,cb[,8kb])
# download file, just process binary file, callback function CB used to process each piece (default size 8kb) of downloaded data
Storbinary (cmd,f[,8kb]) #处理二进制文件, to be given an object F, upload block BS size default 8kb
3 Client FTP instance
1 ImportFtplib2 ImportSocket3 ImportOS4 5 6Host ='Ftp,website'7Dirn ='Filedir'8Files ='filename'9 Ten One defMain (): A Try: -f =Ftplib. FTP (host) - except(Socket.error, Socket.gaierror) as E: the Print('error:cannot Reach "%s"'%host) - return - Print('***connected to Hos "%s"'%host) - + Try: - F.login () + exceptFtplib.error_perm: A Print('Error:cannot Login anonymously') at f.quit () - return - Print('***logged in as "anonymous"') - - Try: - f.cwd (Dirn) in exceptFtplib.error_perm: - Print('error:cannot CD to "%s"'%Dirn) to f.quit () + return - Print('***changed to "%s" folder'%Dirn) the * Try: $F.retrbinary ('retr%s'% files, open (Files,'WB'). Write)Panax Notoginseng exceptFtplib.error_perm: - Print('error:cannot Read Files "%s"'%files) the os.unlink (Files) + Else: A Print('***downloaded "%s" to cmd'%files) the f.quit () + - if __name__=='__main__':#the usual way to run stand-alone scripts $ Main ()
Python and FTP