לדלג לתוכן

8.2 שרת קבצים פתרון

תקיית סנכרון

import os
import ftputil

def synchronize_files(local_dir, remote_dir, host, username, password):
    try:
        # Connect to FTP server
        with ftputil.FTPHost(host, username, password) as ftp:
            print("Connected to FTP server successfully.")

            # List files in local directory
            local_files = set(os.listdir(local_dir))

            # List files in remote directory
            remote_files = set(ftp.listdir(remote_dir))

            # Files to upload (present locally but not on server)
            files_to_upload = local_files - remote_files
            for file in files_to_upload:
                ftp.upload(os.path.join(local_dir, file), os.path.join(remote_dir, file))
                print(f"Uploaded file '{file}' to remote directory.")

            # Files to download (present on server but not locally)
            files_to_download = remote_files - local_files
            for file in files_to_download:
                ftp.download(os.path.join(remote_dir, file), os.path.join(local_dir, file))
                print(f"Downloaded file '{file}' from remote directory.")

        print("File synchronization completed successfully.")

    except Exception as e:
        print(f"Error: {e}")

def main():
    # FTP server details
    host = 'ftp.example.com'
    username = 'your_username'
    password = 'your_password'

    # Local and remote directories
    local_dir = '/path/to/local/directory'
    remote_dir = '/path/to/remote/directory'

    synchronize_files(local_dir, remote_dir, host, username, password)

if __name__ == "__main__":
    main()