-
Notifications
You must be signed in to change notification settings - Fork 0
/
backup
executable file
·273 lines (220 loc) · 7.87 KB
/
backup
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
#!/usr/bin/env python3
import os
import sys
import time
import cmd
import json
script_path = ""
config_file_path = ""
sources = []
raw_sources = []
destinations = []
raw_destinations = []
mountpoints = []
commands = []
dry_commands = []
stub = "rsync -av --progress "
dry_stub = "rsync -avn "
selected = []
def readable_time(sec_elapsed):
h = int(sec_elapsed / (60 * 60))
m = int((sec_elapsed % (60 * 60)) / 60)
s = sec_elapsed % 60.
return "{}:{:>02}:{:>05.2f}".format(h, m, s)
def process_arguments(arguments):
args = arguments.split()
ints = []
for i in args:
ints.append(int(i))
return list(set(ints))
def select_available():
global selected
if selected:
unfiltered = selected
selected = []
for i in unfiltered:
if os.path.isdir(raw_sources[i - 1]) and os.path.isdir(raw_destinations[i - 1]):
selected.append(i)
print("Selection automatically narrowed to available locations.")
print(selected)
if not selected:
for i in range(0, len(sources)):
if os.path.isdir(raw_sources[i]) and os.path.isdir(raw_destinations[i]):
selected.append(i + 1)
print("Selection automatically narrowed to available locations.")
print(selected)
class BackupConsole(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
self.completekey = 'tab'
self.prompt = "> "
self.intro = "rsync backup utility (v1.8)\n---------------------------"
def exit(exit_code):
sys.exit(exit_code)
def do_history(self, args):
"""Shows the command history."""
print(self._hist)
def do_exit(self, args):
"""Exits from the console."""
return -1
def do_clear(self, args):
"""Shortcut for '!clear', clears the screen."""
os.system("clear")
def do_ls(self, args):
"""Lists the backup volumes required."""
print("Required volumes:")
for i in range(0, len(mountpoints)):
print(str(i + 1) + ": " + mountpoints[i])
def do_commands(self, args):
"""Print the constructed rsync commands."""
if not selected:
print("Listed commands:")
for i in range(0, len(commands)):
print(str(i + 1) + ": " + commands[i])
else:
print("Selected commands:")
for i in selected:
print(str(i) + ": " + commands[i - 1])
def do_locations(self, args):
"""Print the selected location pairs."""
if not selected:
print("Listed location pairs:")
for i in range(0, len(sources)):
print(str(i + 1) + ": " + sources[i] + " --> " + destinations[i])
else:
print("Selected location pairs:")
for i in selected:
print(str(i) + ": " + sources[i - 1] + " --> " + destinations[i - 1])
def do_available(self, args):
"""Selects all the available location pairs."""
select_available()
def do_backup(self, args):
"""rsync the selected location pairs."""
select_available()
if not selected:
before = time.time()
for command in commands:
print("Syncing location " + str(commands.index(command) + 1) + "/" + str(len(commands)) + "...")
os.system(command)
print("")
after = time.time()
diff = after - before
print("Completed in " + readable_time(diff) + " h/mm/ss.")
else:
before = time.time()
for i in selected:
print("Syncing location " + str(i) + "/" + str(len(commands)) + "...")
os.system(commands[i - 1])
print("")
after = time.time()
diff = after - before
print("Completed in " + readable_time(diff) + " h/mm/ss.")
def do_dryrun(self, args):
"""rsync dry-run the selected location pairs."""
select_available()
if not selected:
before = time.time()
for command in dry_commands:
print("Syncing location " + str(dry_commands.index(command) + 1) + "/" + str(len(dry_commands)) + "...")
os.system(command)
print("")
after = time.time()
diff = after - before
print("Completed in " + readable_time(diff) + " h/mm/ss.")
else:
before = time.time()
for i in selected:
print("Syncing location " + str(i) + "/" + str(len(dry_commands)) + "...")
os.system(dry_commands[i - 1])
print("")
after = time.time()
diff = after - before
print("Completed in " + readable_time(diff) + " h/mm/ss.")
def do_select(self, args):
"""Select the given location pairs for backup."""
global selected
if selected:
selected = []
arguments = args.split()
if not arguments:
processed = process_arguments(input("Specify which volumes to select... "))
else:
processed = process_arguments(args)
for i in processed:
selected.append(i)
print("Selected locations: " + str(selected))
def do_deselect(self, args):
"""Clear the selection."""
global selected
selected = []
print("Selection cleared.")
def do_shell(self, args):
"""Pass command to a system shell when line begins with '!'"""
os.system(args)
def preloop(self):
global script_path
global config_file_path
global sources
global raw_sources
global destinations
global raw_destinations
global mountpoints
global commands
global dry_commands
global stub
script_path = os.path.dirname(__file__)
config_file_path = os.path.join(script_path, "config", "locations.json")
print("Module is in " + script_path)
print("locations.json is at " + config_file_path)
print("Reading configuration file...")
with open(config_file_path) as config:
content = config.read()
json_locations = json.loads(content)
for loc in json_locations:
raw_sources.append(loc["src"])
raw_destinations.append(loc["dst"])
print("Parsing locations...")
raw_mountpoints = []
for path in raw_sources:
raw_mountpoints.append(path.split('/')[2])
for path in raw_destinations:
raw_mountpoints.append(path.split('/')[2])
mountpoints = list(set(raw_mountpoints))
for path in raw_sources:
sources.append(path.replace(" ", "\\ "))
for path in raw_destinations:
destinations.append(path.replace(" ", "\\ "))
if len(sources) != len(destinations):
print("Parsing error occured. Exiting...")
exit(1)
if len(sources) == 0:
print("None available. Exiting...")
exit(2)
print("Constructing commands...")
for i in range(0, len(sources)):
commands.append(stub + sources[i] + " " + destinations[i])
dry_commands.append(dry_stub + sources[i] + " " + destinations[i])
print("Configuring...")
cmd.Cmd.preloop(self)
self._hist = []
self._locals = {}
self._globals = {}
os.system("clear")
def postloop(self):
cmd.Cmd.postloop(self)
print("Exiting...")
os.system("clear")
def precmd(self, line):
self._hist += [line.strip()]
return line
def postcmd(self, stop, line):
if not line == "clear":
print("")
return stop
def emptyline(self):
pass
def default(self, line):
print(str(line) + ": command not found")
if __name__ == '__main__':
console = BackupConsole()
console.cmdloop()