1
+ import os
2
+ import paramiko
3
+
4
+ # 服务器配置,根据您的需求修改
5
+ server_list = [
6
+ {"name" : "美国" , "ip" : "1.1.1.1" , "port" : 22 , "username" : "root" , "password" : "123456" , "remote_path" : "/home/" },
7
+ #{"name": "美国", "ip": "1.1.1.1", "port": 22, "username": "root", "password": "123456", "remote_path": "/home/"},
8
+
9
+ # 添加更多服务器配置
10
+ ]
11
+
12
+ # 本地目录路径,根据您的需求修改
13
+ local_path = r"D:\kejilion\yyds"
14
+
15
+ def upload_to_remote (local_path , server ):
16
+ ssh = paramiko .SSHClient ()
17
+ ssh .set_missing_host_key_policy (paramiko .AutoAddPolicy ())
18
+
19
+ print ("连接服务器:" , server ["name" ])
20
+ # 连接远程服务器
21
+ ssh .connect (server ["ip" ], server ["port" ], server ["username" ], server ["password" ])
22
+
23
+ print ("创建所需目录" )
24
+ # 递归创建远程服务器上的内部目录
25
+ for root , dirs , files in os .walk (local_path ):
26
+ for dir in dirs :
27
+ remote_dir_path = os .path .join (server ["remote_path" ], os .path .relpath (os .path .join (root , dir ), local_path )).replace ("\\ " , "/" )
28
+
29
+ # 检查远程目录是否存在,如果不存在则创建
30
+ try :
31
+ sftp = ssh .open_sftp ()
32
+ sftp .stat (remote_dir_path )
33
+ sftp .close ()
34
+ except IOError :
35
+ ssh .exec_command ("mkdir -p {}" .format (remote_dir_path ))
36
+
37
+ sftp = ssh .open_sftp ()
38
+
39
+ total_files = sum ([len (files ) for _ , _ , files in os .walk (local_path )])
40
+ uploaded_files = 0
41
+
42
+ print ("开始传输文件" )
43
+ for root , dirs , files in os .walk (local_path ):
44
+ for file in files :
45
+ local_file_path = os .path .join (root , file )
46
+ remote_file_path = os .path .join (server ["remote_path" ], os .path .relpath (local_file_path , local_path )).replace ("\\ " , "/" )
47
+
48
+ # 检查远程文件是否存在,以及大小和修改时间是否变动
49
+ try :
50
+ remote_file_stat = sftp .stat (remote_file_path )
51
+ local_file_stat = os .stat (local_file_path )
52
+
53
+ if remote_file_stat .st_size == local_file_stat .st_size and \
54
+ remote_file_stat .st_mtime >= local_file_stat .st_mtime :
55
+ print ("跳过文件:" , local_file_path ) # 文件大小和修改时间未变动,跳过传输
56
+ continue
57
+ except IOError :
58
+ pass
59
+
60
+ print ("传输文件:" , local_file_path , " -> " , remote_file_path )
61
+ sftp .put (local_file_path , remote_file_path )
62
+ uploaded_files += 1
63
+ print ("传输进度:{}/{}" .format (uploaded_files , total_files )) # 显示上传进度
64
+ print ("传输完成" )
65
+
66
+
67
+ sftp .close ()
68
+ ssh .close ()
69
+
70
+ # 上传文件到每个远程服务器
71
+ for server in server_list :
72
+ upload_to_remote (local_path , server )
73
+
74
+
75
+ # 等待用户按下任意键后关闭窗口
76
+ input ("按任意键关闭窗口..." )
0 commit comments