SFTP Automation

Article Content


SFTP Automation is a python script that watching for changes in specific directory.
It transfer new, or modified files to specififc FTP server.

Requires python modules:
- Watchdog (pip install watchdog)
- pysftp (pip install pysftp)

Running:
python <script_file_name> <dir_to_watch>

Example of running:

ftp-auto-example



Code:


import time, sys
import pysftp
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler

### sftp connection variables ###
sftp_host = ''
sftp_user = ''
sftp_password = ''
sftp_path_dir = ''  # path on sftp, leave empty if target is root

class MyHandler(PatternMatchingEventHandler):
    # regex pattern for watching files, * will detect all, can be changed to all regex patterns
    patterns = ["*"]

    def send_to_ftp(self,file):
        with pysftp.Connection(sftp_host, sftp_user, sftp_password) as sftp:  #make connection
            with sftp.cd(sftp_path_dir):  #go to target dir on ftp
                sftp.put(file, preserve_mtime=True) #send file

    def process(self, event):
        """
        event.event_type
            'modified' | 'created' | 'moved' | 'deleted'
        event.is_directory
            True | False
        event.src_path
            path/to/observed/file
        """
        # the file will be processed there
        print (event.src_path, event.event_type)  # print now only for degug
        
        self.send_to_ftp(event.src_path)

    def on_modified(self, event):
        self.process(event)

    def on_created(self, event):
        self.process(event)

if __name__ == '__main__':
    args = sys.argv[1:]
    observer = Observer()
    observer.schedule(MyHandler(), path=args[0] if args else '.')
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()
    

SubArticles


About

Added by dominik

Date: Feb. 7, 2018, 3:21 p.m.

Comments