行业知识
windows 两个服务器远程文件夹同步,支持文件新增文件同步、修改文件同步、删除文件同步,根据文件大小和时间戳判断文件是否修改 python脚本
2026-11-15 19:23:48
来源:互联网转载
在Python��实现Windows两个服务器之间的文件夹同步,包括文件新增、修改和删除的同步,可以使用paramiko库进行SSH连接以及SFTP传输,并结合文件大小和时间戳判断文件是否发生过变化。以下是包含删除文件同步逻辑的完整脚本示例:
()import osimport paramiko# 定义源与目标服务器信息src_host = 'source_server_ip'src_user = 'source_username'src_password = 'source_password'src_folder = '/path/to/source/folder'dst_host = 'destination_server_ip'dst_user = 'destination_username'dst_password = 'destination_password'dst_folder = '/path/to/destination/folder'def sync_files(sftp_src, src_path, sftp_dst, dst_path): # 遍历源目录下的所有项(文件或子目录) for src_name in sftp_src.listdir_attr(src_path): src_item_path = os.path.join(src_path, src_name.filename) dst_item_path = os.path.join(dst_path, src_name.filename) if S_ISDIR(src_name.st_mode): # 如果是目录 if not sftp_dst.exists(dst_item_path): # 目录不存在于目标服务器,则创建 sftp_dst.mkdir(dst_item_path) sync_files(sftp_src, src_item_path, sftp_dst, dst_item_path) else: # 是文件 if not sftp_dst.exists(dst_item_path): # 文件不存在于目标服务器,直接上传 sftp_dst.put(src_item_path, dst_item_path) else: # 文件存在时比较大小和时间戳 dst_stat = sftp_dst.stat(dst_item_path) if src_name.st_size != dst_stat.st_size or src_name.st_mtime != dst_stat.st_mtime: # 大小或时间戳不同,更新文件 sftp_dst.remove(dst_item_path) sftp_dst.put(src_item_path, dst_item_path) # 处理源服务器上已删除但目标服务器上仍存在的文件 for dst_name in sftp_dst.listdir_attr(dst_path): dst_item_path = os.path.join(dst_path, dst_name.filename) if not sftp_src.exists(os.path.join(src_path, dst_name.filename)): # 源服务器上不存在此文件,从目标服务器上删除 sftp_dst.remove(dst_item_path)def main(): ssh_src = paramiko.SSHClient() ssh_dst = paramiko.SSHClient() # 自动添加主机密钥到known_hosts ssh_src.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_dst.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_src.connect(src_host, username=src_user, password=src_password) ssh_dst.connect(dst_host, username=dst_user, password=dst_password) sftp_src = ssh_src.open_sftp() sftp_dst = ssh_dst.open_sftp() sync_files(sftp_src, src_folder, sftp_dst, dst_folder) sftp_src.close() sftp_dst.close() ssh_src.close() ssh_dst.close()if __name__ == "__main__": main()
这个脚本首先遍历源文件夹中的所有文件和子目录,并根据文件状态进行相应操作。接着,它会检查目标文件夹中是否存在源文件夹中已经删除的文件,并执行删除操作以保持两台服务器上的文件内容一致。
遇到问题
AttributeError: ‘SFTPClient‘ object has no attribute ‘exists‘问题解决-CSDN博客
()上一篇:临时服务器怎么制作?
下一篇:用友软件怎么进入服务器?