1. #!/usr/bin/python

  2. #-*- coding: utf-8 -*-

  3. from ftplib import FTP  

  4. def ftpconnect()  

  5.    ftp_server = 'ftp.python.org'

  6.    username = '*****'

  7.    password = ******''

  8.    ftp=FTP()  

  9.    ftp.set_debuglevel(2) #打开调试级别2,显示详细信息

  10.    ftp.connect(ftp_server,21) #连接

  11.    ftp.login(username,password) #登录,如果匿名登录则用空串代替即可

  12. return ftp  

  13. def downloadfile()  

  14.    remotepath = "/home/pub/dog.jpg";  

  15.    ftp = ftpconnect()  

  16. print ftp.getwelcome() #显示ftp服务器欢迎信息

  17.    bufsize = 1024#设置缓冲块大小

  18.    localpath = 'f:\\test\\dog.jpg'

  19.    fp = open(localpath,'wb') #以写模式在本地打开文件

  20.    ftp.retrbinary('RETR ' + remotepath,fp.write,bufsize) #接收服务器上文件并写入本地文件

  21.    ftp.set_debuglevel(0) #关闭调试

  22.    fp.close()  

  23.    ftp.quit() #退出ftp服务器

  24. <br>  

  25. def uploadfile()  

  26.    remotepath = "/home/pub/dog.jpg"

  27.    ftp = ftpconnect()  

  28.    bufsize = 1024

  29.    localpath = 'f:\\test\\dog.jpg'

  30.    fp = open(localpath,'rb')  

  31.    ftp.storbinary('STOR '+ remotepath ,fp,bufsize) #上传文件

  32.    ftp.set_debuglevel(0)  

  33.    fp.close() #关闭文件

  34.    ftp.quit()  

  35. <br>  

  36. <br>  

  37. <pre name="code"class="python"></pre>  

  38. <pre></pre>  

  39. <pre></pre>