import os import time import paramiko from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler # 配置SFTP连接信息 HOST = 'source_host' PORT = 22 USERNAME = 'your_username' PASSWORD = 'your_password' DEST_HOST = 'destination_host' # 创建SFTP客户端 def connect_sftp(): private_key = paramiko.RSAKey.from_private_key_file('/path/to/your/private/key') client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(HOST, PORT, USERNAME, pkey=private_key) transport = client.get_transport() sftp = paramiko.SFTPClient.from_transport(transport) return sftp # 文件变化时的处理函数 class FileEventHandler(FileSystemEventHandler): def on_modified(self, event): sftp = connect_sftp() super(FileEventHandler, self).on_modified(event) if event.src_path[0] != '.': # 忽略隐藏文件 remote_path = event.src_path.replace('/path/to/watch', '') sftp.put(event.src_path, remote_path) # 上传文件到目标服务器 if __name__ == "__main__": path = '/path/to/watch' # 要监控的本地路径 event_handler = FileEventHandler() observer = Observer() observer.schedule(event_handler, path, recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
下一篇:已经是最后一篇