ftpUpload.py
#coding:utf8
#author:lcamry
import os
import sys
import pyinotify
from ftplib import FTP
WATCH_PATH = './' #監控目錄
def ftp_connect(host, username, password):
ftp = FTP()
# ftp.set_debuglevel(2)
ftp.connect(host, 21)
ftp.login(username, password)
return ftp
"""
從ftp服務器下載文件
"""
def download_file(ftp, remotepath, localpath):
bufsize = 1024
fp = open(localpath, 'wb')
ftp.retrbinary('RETR ' + remotepath, fp.write, bufsize)
ftp.set_debuglevel(0)
fp.close()
"""
從本地上傳文件到ftp
"""
def upload_file(ftp, remotepath, localpath):
bufsize = 1024
fp = open(localpath, 'rb')
ftp.storbinary('STOR ' + remotepath, fp, bufsize)
ftp.set_debuglevel(0)
fp.close()
if not WATCH_PATH:
print('Error',"The WATCH_PATH setting MUST be set.")
sys.exit()
else:
if os.path.exists(WATCH_PATH):
print('Watch status','Found watch path: path=%s.' % (WATCH_PATH))
else:
print('Error','The watch path NOT exists, watching stop now: path=%s.' % (WATCH_PATH))
sys.exit()
class OnIOHandler(pyinotify.ProcessEvent):
ftp=""
def __init__(self):
self.ftp = ftp_connect("10.10.1.22", "ftptest", "ftptest@123")
self.ftp.cwd("./xdroutput")
def process_IN_CLOSE_WRITE(self, event):
print(self.ftp)
upload_file(self.ftp, event.name, os.path.join(event.path,event.name))
print('Action',"close file: %s " % os.path.join(event.path,event.name))
def process_IN_MOVED_TO(self, event):
print(self.ftp)
upload_file(self.ftp, event.name, os.path.join(event.path,event.name))
print('Action',"move file: %s " % os.path.join(event.path,event.name))
def auto_compile(path = '.'):
wm = pyinotify.WatchManager()
mask = pyinotify.IN_CLOSE_WRITE | pyinotify.IN_MOVED_TO
notifier = pyinotify.ThreadedNotifier(wm, OnIOHandler())
notifier.start()
wm.add_watch(path, mask,rec = True,auto_add = True)
print('Start Watch','Start monitoring %s' % path)
while True:
try:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
notifier.stop()
break
if __name__ == "__main__":
auto_compile(WATCH_PATH)
使用方式
python ftpUpload.py