#!/usr/bin/python #Filename: ftp_trans.py #author: hjlin #date: 2009-05-25
'''\ Ftp transfer client
brief put files from machine A to machine B '''
#function get_tasks() start def get_tasks(conf_file = '../etc/ftp_trans.conf') :
#create task tasks = []
try : fp = file(conf_file, 'r') except : print 'open file', conf_file, 'failed' return tasks
#read task config while True :
line = fp.readline()
if len(line) == 0 : break
#skip comment if line.startswith('#') : continue
#replace all '\r' line = line.replace('\r', '')
#replace all '\n' line = line.replace('\n', '')
#split to a task by '\t' task = line.split('\t')
#delete null column for loop in range(0, len(task)): if loop >= len(task) : break if len(task[loop]) == 0 : del task[loop]
#skip invalid task if len(task) != 4 : continue
#add task tasks.append(task)
return tasks #function get_tasks() end
#function do_task() start def do_task(task) :
print 'Now do_task :', task
#get task type type = task[0]
if type == 'put' : #get src_dir src_dir = task[1]
#get dst_dir and server_ip pair = task[2].split(':')
if len(pair) != 2 : print 'parse task failed, invalid server_ip or dst_dir', task[2] return
server_ip = pair[0]
dst_dir = pair[1]
#get username and password pair = task[3].split('/')
if len(pair) != 2 : print 'parse task failed, invalid username or password', task[3] return
username = pair[0]
password = pair[1]
if not put_task(src_dir, dst_dir, server_ip, username, password) : print 'put task failed ...' return
elif type == 'get' :
print 'get task' return
else : print 'parse task failed, error type : ', type return
return #function do_task() end
#function put_task() start def put_task(src_dir, dst_dir, server_ip, username, password) :
import os
#change current work directory try : os.chdir(src_dir) except : print 'chdir failed : ', src_dir return False
#open ftp import ftplib
ftp = ftplib.FTP() #ftp.set_debuglevel(2)
#connect server try : ftp.connect(server_ip, 21) except : print 'connect server ', server_ip, ':', 21, ' failed' return False
#login try : ftp.login(username, password) except : print 'login server with ', username , '/', password, ' failed' return False
#change work directory try : ftp.cwd(dst_dir) except : print 'cwd dir : ', dst_dir, ',failed' return False
#put files in src_dir for file in os.listdir(src_dir) : #skip directory if os.path.isdir(file) : print 'file , ', file , ' is a directory , continue ...' continue
#open local file try : fp = open(file, 'rb') except : print 'open file failed , ', file continue
#put local file try : ftp.storbinary('STOR ' + file,fp) except : print 'put file faild', file continue
#delete local file os.remove(file)
return True #function put_task() end
#main function from here
import os import time
print '--------------------------------------' print 'ftp trans start ....'
#read all tasks tasks = get_tasks()
print 'All tasks = ', tasks
#do all tasks in loop while True : for task in tasks : do_task(task)
time.sleep(10)
print 'ftp trans end ....'
|