Skynet

          ---------- ---------- 我的新 blog : liukaiyi.cublog.cn ---------- ----------

            BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
            112 Posts :: 1 Stories :: 49 Comments :: 0 Trackbacks


          ftplib模塊定義了FTP類和一些方法,用以進行客戶端的ftp編程。可以用python編寫一個自已的ftp客戶端程序,用于下載文件或鏡像站點。如果想了解ftp協議的詳細內容,請參考RFC959。

          該模塊是python的通用模塊,所以默認應該已安裝。ftplib模塊使用很簡單,暫時只有一個FTP類和十幾個函數。

          下面用一個交互方式演示一下ftplib的主要功能。

          >>> from ftplib import FTP
          >>> ftp = FTP('ftp.cwi.nl')   # connect to host, default port
          >>> ftp.login()               # user anonymous, passwd anonymous@
          >>> ftp.retrlines('LIST')     # list directory contents
          total 24418
          drwxrwsr-x   5 ftp-usr  pdmaint     1536 Mar 20 09:48 .
          dr-xr-srwt 105 ftp-usr  pdmaint     1536 Mar 21 14:32 ..
          -rw-r--r--   1 ftp-usr  pdmaint     5305 Mar 20 09:48 INDEX
           .
           .
           .
          >>> ftp.retrbinary('RETR README', open('README', 'wb').write)
          '226 Transfer complete.'
          >>> ftp.quit()



          下面一個下載文件的示例

          #!/usr/bin/env python

          #author:Jims of 
          http://www.ringkee.com/
          #create date: 2005/02/05
          #description: Using ftplib module download a file from a ftp server.

          from ftplib import FTP

          ftp=FTP()

          ftp.set_debuglevel(2) #打開調試級別2,顯示詳細信息
          ftp.connect('ftp_server','port') #連接
          ftp.login('username','password') #登錄,如果匿名登錄則用空串代替即可

          print ftp.getwelcome() #顯示ftp服務器歡迎信息
          ftp.cwd('xxx/xxx/') #選擇操作目錄
          bufsize = 1024 #設置緩沖塊大小
          filename='dog.jpg' 
          file_handler = open(filename,'wb').write #以寫模式在本地打開文件
          ftp.retrbinary('RETR dog.jpg',file_handler,bufsize) #接收服務器上文件并寫入本地文件
          ftp.set_debuglevel(0) #關閉調試

          ftp.quit() #退出ftp服務器

          下面一個上傳文件的示例,要成功運行該腳本,需在ftp服務器上有上傳文件的權限。

          #!/usr/bin/env python

          #author:Jims of 
          http://www.ringkee.com/
          #create date: 2005/02/05
          #description: Using ftplib module upload a file to a ftp server.

          from ftplib import FTP

          ftp=FTP()

          ftp.set_debuglevel(2)
          ftp.connect('ftp_server','port')
          ftp.login('username','password')

          print ftp.getwelcome()
          ftp.cwd('xxx/xxx/')
          bufsize = 1024
          filename='dog.jpg'
          file_handler = open(filename,'rb')
          ftp.storbinary('STOR dog.jpg',file_handler,bufsize) #上傳文件
          ftp.set_debuglevel(0)

          file_handler.close() #關閉文件
          ftp.quit()


          整理 www.aygfsteel.com/Good-Game
          posted on 2009-07-10 12:14 劉凱毅 閱讀(1737) 評論(0)  編輯  收藏 所屬分類: python
          主站蜘蛛池模板: 紫云| 淮阳县| 石首市| 平江县| 元朗区| 隆尧县| 宁海县| 南和县| 东乡族自治县| 宣化县| 马关县| 蕉岭县| 拜泉县| 连南| 武城县| 中西区| 通州市| 江安县| 清河县| 利津县| 都江堰市| 鸡东县| 湘乡市| 凤冈县| 军事| 古田县| 万载县| 遂宁市| 南木林县| 聊城市| 台东市| SHOW| 新巴尔虎右旗| 永仁县| 吴堡县| 义马市| 灵璧县| 迁西县| 北碚区| 龙南县| 台南市|