Created
December 19, 2018 03:12
-
-
Save choidslab/313529454623bcdc8ed590bd7e090530 to your computer and use it in GitHub Desktop.
FTP 파일 자동 업로더 스크립트
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import os | |
import time | |
import getpass | |
from ftplib import FTP | |
from tqdm import tqdm | |
from watchdog.observers import Observer | |
from watchdog.events import FileSystemEventHandler | |
# import threading | |
# import multiprocessing | |
# FTP server 원격 경로 및 파일 경로 설정 | |
Rpath = "/test/" | |
Lpath = "/test/" | |
# Variables FTP User ID, Password | |
username = "" | |
password = "" | |
class Watcher: | |
# Set Monitoring Directory | |
DIRECTORY_TO_WATCH = Lpath | |
def __init__(self): | |
self.observer = Observer() | |
def run(self): | |
# 이벤트 핸들러 객체 생성 | |
event_handler = Handler() | |
self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True) | |
self.observer.start() | |
print("###### Start Monitoring ######") | |
try: | |
while True: | |
time.sleep(1) | |
except KeyboardInterrupt: | |
self.observer.stop() | |
self.observer.join() | |
# Handler Class | |
class Handler(FileSystemEventHandler): | |
@staticmethod | |
def on_any_event(event): | |
if event.is_directory: | |
return None | |
elif event.event_type == 'created': # 파일 생성 이벤트가 발생할 경우 해당 부분 처리 | |
print("Created - %s." % event.src_path) | |
# 파일확장명, 파일명, 파일경로 추출 | |
ext = os.path.splitext(event.src_path)[-1] | |
filename = event.src_path.split('/')[-1] | |
dirname = event.src_path.split('/')[-2] | |
# 파일이 새롭게 생성될 경우, 복사되는 시간을 기다리기 위한 코드 | |
# (특정 경로에 파일을 복사할 경우, 복사되는 중간에 open()에 의해 파일에 접근할 경우 에러가 발생하기 때문에 이 코드를 사용) | |
if os.path.getsize(event.src_path) >= 1073741824: | |
time.sleep(10) | |
else: | |
time.sleep(5) | |
# 파일확장명이 '.mp4'인 경우 ftp upload 수행 | |
if ext == '.mp4': | |
ftp_upload(filename, dirname, event.src_path) | |
else: | |
pass | |
else: | |
return None | |
# 파일 업로드 함수 | |
def ftp_upload(filename, dirname, eventpath): | |
# Login to ftp server. | |
ftp = FTP("ftp server addrees") | |
ftp.login(username, password) | |
# 파일 열기, 파일 크기 가져오기 | |
file = open(eventpath, 'rb') | |
filesize = os.path.getsize(eventpath) | |
# Set upload path - Server path | |
ftp.cwd(Rpath + dirname + "/") | |
# 파일 업로드 수행(tqdm - progress bar 생성, ftp.storbinary() 파일 업로드 수행) | |
with tqdm(unit='blocks', unit_scale=True, leave=False, miniters=1, desc="Uploading...", | |
total=filesize) as tqdm_instance: | |
ftp.storbinary('STOR ' + filename, file, 20480, callback=lambda sent: tqdm_instance.update(len(sent))) | |
print("\nFile transfer successful.\n") | |
# Close connection | |
ftp.quit() | |
# Close file | |
file.close() | |
# ID/PW 체크 함수 생략 | |
# def check_account(): | |
# | |
if __name__ == '__main__': | |
w = Watcher() | |
w.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment