Repository navigation
Expand file tree
/
Copy pathbackup
More file actions
executable file
·245 lines (201 loc) · 7.83 KB
/
Copy pathbackup
File metadata and controls
executable file
·245 lines (201 loc) · 7.83 KB
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
#!/usr/bin/env python3
import os
import json
import subprocess
import datetime
import argparse
from pathlib import Path
CONFIG_FILE = os.path.expanduser("~/.config/systemd-backup/backup.json")
PASSPHRASE_FILE = os.path.expanduser("~/.config/systemd-backup/.secret")
INCLUDE_FILE = os.path.expanduser("~/.config/systemd-backup/include")
EXCLUDE_FILE = os.path.expanduser("~/.config/systemd-backup/exclude")
PREPARE_REMOTES = os.path.expanduser("~/.config/systemd-backup/prepare-remotes.sh")
TMP_IN_PROGRESS = "/tmp/backup-in-progress"
def resolve(path):
return os.path.expanduser(path)
def read_config():
if not os.path.isfile(CONFIG_FILE):
print(f"Configuration file not found: {CONFIG_FILE}")
return None
if not os.path.isfile(PASSPHRASE_FILE):
print(f"Secret file not found: {PASSPHRASE_FILE}")
print("Make sure the secret file does not end in new line!")
return None
with open(CONFIG_FILE) as f:
try:
config = json.load(f)
except json.JSONDecodeError as e:
print(f"Error parsing configuration file: {e}")
return None
source_paths = list(map(resolve, config.get("source_paths", [])))
backup_location = resolve(config.get("backup_location"))
backup_remotes = config.get("backup_remotes", [])
archive_age_days = config.get("archive_age_days", 30)
if not backup_location:
print("Backup location not specified in the configuration file.")
return None
if not os.path.isdir(backup_location):
print(f"Creating backup location: {backup_location}")
os.makedirs(backup_location)
return source_paths, backup_location, backup_remotes, archive_age_days
def execute_rsync(source_paths, backup_location):
rsync_command = [
"rsync",
"-a",
"--progress",
"--relative",
"--delete",
"--delete-delay",
"--delete-excluded",
"--prune-empty-dirs"
]
if os.path.isfile(INCLUDE_FILE):
rsync_command.append(f"--include-from={INCLUDE_FILE}")
if os.path.isfile(EXCLUDE_FILE):
rsync_command.append(f"--exclude-from={EXCLUDE_FILE}")
if source_paths:
for source_path in source_paths:
rsync_command.append(f"{source_path}/")
rsync_command.append(f"{backup_location}/")
print(f"Starting backup, executing: {rsync_command}")
print(f"Backup location: {backup_location}")
try:
subprocess.run(rsync_command, check=True)
except subprocess.CalledProcessError as e:
print(f"Error running rsync command: {e}")
return False
print("Backup completed.")
return True
def bundle_and_encrypt_backup(backup_location):
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
root = os.path.dirname(backup_location)
filename = os.path.basename(backup_location)
os.makedirs(f"{root}/archive", exist_ok=True)
destination = f"{root}/archive/{filename}-{timestamp}.tar.gz.gpg"
with open(PASSPHRASE_FILE, "r") as file:
passphrase = file.read()
print(f"Bundling {backup_location} to {destination}")
bundle_command = [
"tar",
"-C",
os.path.dirname(backup_location),
"-zcv",
os.path.basename(backup_location)
]
encrypt_command = [
"gpg",
"--batch",
"--symmetric",
"--cipher-algo=AES256",
f"--passphrase={passphrase}",
"-o",
destination
]
try:
tar_ps = subprocess.Popen(bundle_command, stdout=subprocess.PIPE)
except subprocess.CalledProcessError as e:
print(f"Error running tar command: {e}")
return None
try:
subprocess.run(encrypt_command, check=True, stdin=tar_ps.stdout)
except subprocess.CalledProcessError as e:
print(f"Error running gpg command: {str(e).replace(passphrase, '*****')}")
return None
print(f"{destination} created!")
return destination
def send_to_remote_backups(encrypted_archive, backup_remotes):
for remote in backup_remotes:
if os.path.isfile(PREPARE_REMOTES):
print(f"detected {PREPARE_REMOTES}, using custom script instead of direct rsync")
rsync_command = [
PREPARE_REMOTES,
encrypted_archive,
f"{remote}/"
]
else:
rsync_command = [
"rsync",
"-zP",
"--progress",
encrypted_archive,
f"{remote}/"
]
try:
subprocess.run(rsync_command, check=True)
except subprocess.CalledProcessError as e:
print(f"Error running rsync command: {e}")
return False
def notify(title, message, display_notification):
if not display_notification:
return
try:
subprocess.run(["notify-send", title, message], check=True)
except subprocess.CalledProcessError as e:
print(f"Error sending notification: {e}")
return
def delete_old_files(directory, days):
current_date = datetime.datetime.now()
root = os.path.dirname(directory)
archive_directory = f"{root}/archive"
for filename in os.listdir(archive_directory):
if filename.startswith('backup-') and filename.endswith('.tar.gz.gpg'):
date_str = filename.split('-')[1].split('.')[0]
file_date = datetime.datetime.strptime(date_str, "%Y%m%d%H%M%S")
if (current_date - file_date).days > days:
file_path = os.path.join(archive_directory, filename)
os.remove(file_path)
print(f"Deleted file: {file_path}")
def main():
config = read_config()
parser = argparse.ArgumentParser(description="Create backups of your linux directories")
parser.add_argument(
"--sync-to-backup",
dest="sync_to_backup",
action='store_true',
required=False,
help="Synchronizes directories to backup directory")
parser.add_argument(
"--bundle-and-encrypt",
dest="bundle_and_encrypt",
action='store_true',
required=False,
help="Bundles and encrypts the backup directory")
parser.add_argument(
"--send-to-remotes",
dest="send_to_remotes",
action='store_true',
required=False,
help="Sends encrypted archive to the backup remotes specified in ~/.config/systemd-backup/backup.json")
parser.add_argument(
"--notify",
dest="notify",
action='store_true',
required=False,
help="Send notification when backup is ongoing or completed"
)
args = parser.parse_args()
try:
with open(TMP_IN_PROGRESS, 'w') as file:
file.write('progress')
notify('systemd-backup', 'Backing up, do not shutdown PC', args.notify)
if config:
source_paths, backup_location, backup_remotes, archive_age_days = config
if args.sync_to_backup:
execute_rsync(source_paths, backup_location)
elif args.bundle_and_encrypt:
encrypted_archive = bundle_and_encrypt_backup(backup_location)
if args.send_to_remotes and encrypted_archive is not None:
send_to_remote_backups(encrypted_archive, backup_remotes)
delete_old_files(backup_location, archive_age_days)
else:
if execute_rsync(source_paths, backup_location):
encrypted_archive = bundle_and_encrypt_backup(backup_location)
if encrypted_archive is not None:
send_to_remote_backups(encrypted_archive, backup_remotes)
delete_old_files(backup_location, archive_age_days)
finally:
with open(TMP_IN_PROGRESS, 'w') as file:
file.write('done')
notify('systemd-backup', 'Backup is complete!', args.notify)
if __name__ == "__main__":
main()