python ftp 上傳下載

#coding=utf-8
 
from ftplib import FTP
import os
import os.path
import shutil
import datetime

 
def ftp_up(filename):
    ftp=FTP() 
    ftp.set_debuglevel(2)#打開調試級別2,顯示詳細信息;0爲關閉調試信息 
    ftp.connect('10.7.39.29','888')#鏈接 
    ftp.login('happ','happ')#登陸,若是匿名登陸則用空串代替便可 
    print ftp.getwelcome()#顯示ftp服務器歡迎信息
    try:
        ftp.mkd('+CYOUEMT')  
    except:  
        print('dir has existed %s' % '+CYOUEMT')

    ftp.cwd('+CYOUEMT') #選擇操做目錄 
    bufsize = 1024#設置緩衝塊大小 
    file_handler = open(filename,'rb')#以讀模式在本地打開文件 
    ftp.storbinary('STOR %s' % os.path.basename(filename),file_handler,bufsize)#上傳文件 
    ftp.set_debuglevel(0) 
    file_handler.close() 
    ftp.quit() 
    print "ftp up OK" 
 
def ftp_down(host,port,user,passw,rootDir,locaDir): 
    ftp=FTP() 
    ftp.set_debuglevel(2) 
    ftp.connect(host,port) 
    ftp.login(user,passw) 
    print ftp.getwelcome()#顯示ftp服務器歡迎信息 
    ftp.cwd(rootDir) #選擇操做目錄 
    files = ftp.nlst()
    for name in files:   
        bufsize = 1024 
        file_handler = open(locaDir + name,'wb').write #以寫模式在本地打開文件 
        ftp.retrbinary('RETR %s' % os.path.basename(name),file_handler,bufsize)#接收服務器上文件並寫入本地文件 
    ftp.set_debuglevel(0) 
    ftp.quit() 
    print "ftp down OK"

def copyFiles(sourceDir,  targetDir): 
    if sourceDir.find(".svn") > 0: 
        return 
    for file in os.listdir(sourceDir): 
        sourceFile = os.path.join(sourceDir,  file) 
        targetFile = os.path.join(targetDir,  file) 
        if os.path.isfile(sourceFile): 
            if not os.path.exists(targetDir):  
                os.makedirs(targetDir)  
            if not os.path.exists(targetFile) or(os.path.exists(targetFile) and (os.path.getsize(targetFile) != os.path.getsize(sourceFile))):  
                    open(targetFile, "wb").write(open(sourceFile, "rb").read()) 
        if os.path.isdir(sourceFile): 
            First_Directory = False 
            copyFiles(sourceFile, targetFile)
    print 'copy them to '+targetDir


#a.com
ftp_down('10.10.10.1','21','111',"123456",'happ','toftp/')
for root,dirs,files in os.walk('toftp'):
    for f in files:
        ftp_up(os.path.join(root,f))

#b.com
相關文章
相關標籤/搜索