# -*- coding: utf-8 -*-
from ftplib import FTP
import traceback
import os
class PyFtpClient():
def __init__( self, ):
self.ftp_core = FTP()
self.ftp_core.set_debuglevel( 2 )
def connect( self, host, port ):
ret = True
try:
self.ftp_core.connect( host, port )
except:
ret = False
return ret
def login( self, user, password ):
ret = True
try:
self.ftp_core.login( user, password )
self.ftp_core.getwelcome()
except:
ret = False
return ret
def set_current_path( self, path ):
nlst = self.ftp_core.nlst()
if not self.list_contain( nlst, path ):
self.ftp_core.mkd( path )
self.ftp_core.cwd( path )
def upload_folder( self, path ):
main_path, folder_name = os.path.split( path )
files = os.listdir( path )
files.sort()
for filename in files:
fullpath = os.path.join( path, filename )
self.upload_file( fullpath )
def quick_upload_file( self, local_file ):
ret = True
path, filename = os.path.split( local_file )
files = self.ftp_core.nlst()
if self.list_contain( files, filename ):
self.ftp_core.delete( filename )
if not os.path.exists( local_file ):
ret = False
else:
self.upload_file( filename, local_file )
return ret
def upload_file( self, file_name, local_path ):
try:
bufsize = 1024
file_handler = open( local_path, 'rb' )
cmd = "STOR %s" % ( file_name )
self.ftp_core.storbinary( cmd, file_handler, bufsize )
except Exception , e:
print e
traceback.print_exc()
def download( self, remote_path, local_file ):
print "not support"
def quit( self ):
self.ftp_core.quit()
def list_contain( self, ls, item ):
ret = True
try:
index = ls.index( item )
except:
ret = False
return ret
cftp = PyFtpClient()
if ( cftp.connect( 'ip', port ) == True ):
if ( cftp.login( 'user', 'password' ) == True ):
cftp.set_current_path( "windows" )
cftp.quick_upload_file( "D:\\data\\1.rar" )
cftp.quick_upload_file( "D:\\data\\2.rar" )
cftp.quick_upload_file( "D:\\data\\3.rar" )
cftp.quick_upload_file( "D:\\data\\4.rar" )
cftp.quit()
else:
print "login error."
else:
print "connect error."
Python FTP 客户端
最新推荐文章于 2023-12-08 12:03:58 发布