Search code examples
pythonftp

Monitor remote FTP directory


I only have FTP access to a directory on a remote server and would like to get the contents of new files as soon as they appear in the directory.

Is there any thing like FAM for Python that lets me monitor for new files over FTP?


Solution

  • If polling the server is an option:

    from ftplib import FTP
    from time import sleep
    
    ftp = FTP('localhost')
    ftp.login()
    
    def changemon(dir='./'):
        ls_prev = set()
    
        while True:
            ls = set(ftp.nlst(dir))
    
            add, rem = ls-ls_prev, ls_prev-ls
            if add or rem: yield add, rem
    
            ls_prev = ls
            sleep(5)
    
    for add, rem in changemon():
        print('\n'.join('+ %s' % i for i in add))
        print('\n'.join('- %s' % i for i in remove))
    
    ftp.quit()