-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmtscp.py
executable file
·326 lines (312 loc) · 11.2 KB
/
mtscp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#!/usr/bin/python
import threading
from threading import Thread, Lock, current_thread, Semaphore
import Queue
import paramiko
import signal
import sys
import time # remove later
import os
import md5
import math
from urlparse import urlparse
import paramiko
import argparse
import re
import itertools
# Constants
CHUNK_SIZE = 1024*1024*5
THREADS = 8
running = True
verbose = False
def debug(str):
if(verbose):
print str
def quit_program():
global running
running = False
for t in sht:
try:
t.stop()
except:
pass
for t in sht:
try:
t.join()
except:
pass
sys.exit(-1)
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
quit_program()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
def scpfile(str):
scpfile_regex = '^((([^:/?#@]+)@)?([^@/?#]*)?:)?(~?([^~#]*))$'
try:
match = re.match(scpfile_regex, str)
obj = {}
obj['path'] = match.group(5)
obj['username'] = match.group(3)
obj['host'] = match.group(4)
except:
msg = "%s does not appear to be a valid path" % str
raise argparse.ArgumentTypeError(msg)
if(obj['host'] and re.match('~.*', obj['path'])):
msg = "expansion of '~' in '%s' currently unsupported" % obj['path']
raise argparse.ArgumentTypeError(msg)
return obj
parser = argparse.ArgumentParser()
parser.add_argument('-r', action='store_true', help="Recursively copy entire directories.")
parser.add_argument('src', metavar='[[user@]host1:]path', type=scpfile, nargs='+', help='')
parser.add_argument('-v', '--verbose', action='store_true', help="Enable verbose loggging")
args = parser.parse_args()
destination = args.src.pop()
source = args.src
if(args.verbose):
verbose = True
class Chunk:
def __init__(self):
self.data=""
self.md5=""
self.path=""
self.dest=""
self.chunk_size=0
self.offset=0
class File:
def __init__(self, src, dest):
self.mutex = Lock()
self.src = src
self.dest = dest
self.mutex = Lock()
class LocalFile(File):
def __init__(self, src, dest):
File.__init__(self, src, dest)
self.dest_created = False
self.open()
def open(self):
self.file = open(self.src, "ab+")
self.file.seek(0, 2)
self.file_size = self.file.tell();
self.file.seek(0)
while(self.file.tell() !=0):
print "waiting on seek"
def __iter__(self):
return self
def next(self):
chunk = Chunk()
self.mutex.acquire()
if not self.file:
self.mutex.release()
raise StopIteration()
chunk.offset = self.file.tell()/CHUNK_SIZE
chunk.size = -self.file.tell()
chunk.data = self.file.read(CHUNK_SIZE)
if not chunk.data:
self.mutex.release()
raise StopIteration()
chunk.size += self.file.tell()
self.mutex.release()
chunk.dest = self.dest
chunk.md5 = md5.new()
chunk.md5.update(chunk.data)
chunk.md5 = str(bytearray(chunk.md5.digest())).encode('hex')
if(chunk.size != CHUNK_SIZE):
print "read chunk %d, size: %d" % (chunk.offset, chunk.size)
sys.exit()
# print "created chunk #%d" % chunk.offset
return chunk
def write(self, offset, data):
self.mutex.acquire()
self.file.seek(offset)
self.file.write(data)
self.mutex.release()
def md5(self, start, size):
m = md5.new()
self.mutex.acquire()
self.file.seek(start)
m.update(self.file.read(size))
self.mutex.release()
return m.digest()
def eof(self):
self.mutex.acquire()
ret = self.file_size == self.file.tell()
self.mutex.release()
return ret
# def dest_created(self, created=None):
# ret = False
# self.mutex.acquire()
# if(created is None):
# ret = self.dest_created
# else
# self.dest_created = CREATED
# ret = True
# self.mutex.release()
# return ret
class LocalDir:
def __init__(self, src, dest):
self.files = []
self.folders = []
self.semaphore = Semaphore(THREADS)
self.current_file = None
for srcdir in src:
print "walking %s" % srcdir
if(os.path.isdir(srcdir['path'])): #it's a direectory, walk it.
for root, subFolders, files in os.walk(srcdir['path']):
print "files: %s, %s, %s" % (root, subFolders, files)
dest_dir = os.path.join(dest['path'], os.path.relpath(root, srcdir['path']))
#only keep the very end folder, cause were going to create dirs with parents.
if(not len(subFolders)):
self.folders.append("'" + dest_dir + "'")
print "dest: %s" % dest_dir
for file in files:
print(file)
filename = os.path.join(srcdir['path'], file)
dest_file = os.path.join(dest_dir, file)
self.files.append(LocalFile(filename, dest_file))
else: #its just a regular file
print os.path.split(srcdir['path'])[1]
dest_file = os.path.join(dest['path'], os.path.split(srcdir['path'])[1])
print "copying %s to %s" % (srcdir['path'], dest_file)
self.files.append(LocalFile(srcdir['path'], dest_file))
#note that this totally ignores maximum command line length (which is huge)
self.folders = " ".join(self.folders)
print "Folders: %s" % self.folders
def __iter__(self):
return self
def next(self):
if(self.current_file is None or self.current_file.eof()):
if(len(self.files)):
self.current_file = self.files.pop()
else:
raise StopIteration()
print "copying file %s" % self.current_file['path']
return self.current_file
class SSH_Thread(Thread):
mutex = Lock()
files = []
current_file = None
def __init__(self, host, username, password, files):
Thread.__init__(self)
print "SSH_Thread constructor"
self.host = host
self.username = username
self.password = password
self.size=0
self.time=0
self.file_list = files
self.ssh = None
def connect(self):
if(self.ssh is not None):
return
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(self.host, username=self.username, password=self.password)
stdin, stdout, stderr = self.ssh.exec_command("which md5")
if(len(stdout.readlines())):
self.md5_cmd = "md5"
else:
self.md5_cmd = "md5sum"
def run(self):
self.connect()
if(not running):
return
print " " + current_thread().getName()
self.running = True
sftp = self.ssh.open_sftp()
if(sftp is None):
print "sftp is null"
#iterate throught my file list
for file in self.file_list.files:
if(not running):
return
scpfile = None
file.mutex.acquire()
#try to get info about the file
try:
stat = sftp.stat(file.dest)
except IOError:
stat = None
#if the file doesn't exist, or is the wrong size, create it.
try:
if(stat is None or stat.st_size != file.file_size):
if(stat is None):
scpfile = sftp.file(file.dest, 'w')
else:
scpfile = sftp.file(file.dest, 'w')
scpfile.seek(file.file_size-1)
scpfile.write('\0')
else:
scpfile = sftp.file(file.dest, 'r+')
except:
print "ERROR: Could not open remote file."
file.mutex.release()
quit_program()
return
file.mutex.release()
#write each chunk to the file.
for chunk in file:
if(not running):
scpfile.close()
return
print "writing chunk %d of %s" % (chunk.offset, file.dest)
#get the md5 of the remote chunk, just in case we have already transferred it.
cmd = "dd if=%s bs=%d skip=%d count=1 | %s" %(file.dest, CHUNK_SIZE, chunk.offset, self.md5_cmd)
stdin, stdout, stderr = self.ssh.exec_command(cmd)
md5 = stdout.readline()[0:32]
#if we haven't transferred it, do it until the md5 matches.
while(md5 != chunk.md5):
if(not running):
scpfile.close()
return
print "trying chunk %d in %s" % (chunk.offset, current_thread().getName())
scpfile.seek(chunk.offset*CHUNK_SIZE)
scpfile.write(chunk.data)
print cmd
stdin, stdout, stderr = self.ssh.exec_command(cmd)
md5 = stdout.readline()[0:32]
print "chunk.md5: %s, md5: %s" %(chunk.md5, md5)
scpfile.close();
print "leaving thread " + current_thread().getName()
def stop(self):
self.kill = True
def mkdir(self, folder):
self.connect()
cmd = "mkdir -p %s" % folder
print cmd
stdin, stdout, stderr = self.ssh.exec_command(cmd)
if(stdout.channel.recv_exit_status()):
print "stub: failed to create remote dir"
return 1
def chunk_write(self, chunk):
ssh_md5=""
while(chunk.md5 != ssh_md5):
try:
print "writing %d bytes - %d" % (len(chunk.data), chunk.offset)
file = self.ssh.open_sftp().file(chunk.dest, 'r+')
file.seek(CHUNK_SIZE*chunk.offset)
file.write(chunk.data)
file.close();
cmd = "dd if='%s' count=1 bs=%d skip=%d | md5sum" % (chunk.dest, CHUNK_SIZE, chunk.offset)
stdin, stdout, stderr = self.ssh.exec_command(cmd)
ssh_md5 = stdout.readline()[0:32]
print "md5: '" + ssh_md5 + "' == '" + chunk.md5 + "' " + `(chunk.md5 == ssh_md5)` + " " + `len(chunk.data)`
print stderr.readlines();
except:
print "some bad shit happened."
self.connect()
# path = "/home/sam/Documents/mtscp/src"
# destination = "/home/sam/Documents/mtscp/dest"
file_list = LocalDir(source, destination)
sht = []
for i in range(0,THREADS):
if(running):
sht.append(SSH_Thread(destination['host'], destination['username'], '', file_list))
if(i==0):
debug("running mkdir on %s" % file_list.folders)
sht[0].mkdir(file_list.folders)
sht[i].start()
for t in sht:
t.join()
print "all threads jioned"
sys.exit()