監控目錄下生成的文件並上傳到ftp

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章