-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwp_backup.py
More file actions
executable file
·496 lines (388 loc) · 19.5 KB
/
wp_backup.py
File metadata and controls
executable file
·496 lines (388 loc) · 19.5 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
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
#!/usr/bin/env python3
from paramiko import SSHClient
import paramiko
import sys
import argparse
from datetime import datetime
import time
import sqlite3
import argcomplete
from pprint import pprint
from collections import OrderedDict
_date = datetime.today()
current_date = _date.strftime("%d-%m-%Y")
port = 12345
def usage_function():
print("#"*50)
print()
print('EXAMPLE COMMAND TO ADD WEBSITE TO DATABASE ')
print()
print("./wp_backup.py --action add_website -u SSH_UserName -d website_name.com -P wordpress-folder-path "
"(Without back slash/ example.com or /home/user/example.com) -p 'PASSWORD' "
"( Always in single quotes to prevent parameter expansion! ) -H HOST/IP ")
print()
print("#"*50)
usage_function()
# (self.password,self.wordpress_path,self.username,self.domain_name)
parser = argparse.ArgumentParser(prog='WordPress Backup tools', description='Backing up WP Remote via SSH Paramiko')
parser.add_argument('-u', '--user', action='store', help='-u username of SSH')
parser.add_argument('-p', '--password', action="store", help='-p add password for SSH')
parser.add_argument('-d', '--domain', action="store", help='-d domain name')
parser.add_argument('-P', '--path', action="store", help='-P domain folder path')
parser.add_argument('-H', '--host', action="store", help='-H hostname for SSH')
# parser.add_argument('-R','--restore',action="store",help='-R Restore Added Wordpress Site From database')
# parser.add_argument('-D','--wp_site',action='store',help='-D/--wp-site Provider domain argument <domain>/<wp_sute>')
parser.add_argument('--action', choices=['backup', 'restore', 'add_website', 'delete_website', 'list_website',
'all_sites', 'check', 'restore2', 'list_website2', 'backup2'], default='check')
argcomplete.autocomplete(parser)
args = parser.parse_args()
exclude_path = ("./wp-content/uploads")
# class WpDatabase():
connection = sqlite3.connect(database='wordpress_support.db')
#########################################################
#########################################################
######## DATABASE INITIATION INSERT ##############
#########################################################
#########################################################
class WpDatabase:
def __init__(self,domain_name,username,password,hostname,wp_path,backup_folder):
self.domain_name = domain_name
self.username = username
self.password = password
self.hostname = hostname
self.wp_path = wp_path
self.backup_folder = backup_folder
#########################################################
#########################################################
######## ADD WORDPRESS SITE TO DATABASE ########
#########################################################
#########################################################
def add_website(self):
add_new_website = f"""
INSERT INTO wordpress_sites(domain_name,username,password,hostname,wp_path,backup_folder)
VALUES('{self.domain_name}',
'{self.username}',
'{self.password}',
'{self.hostname}',
'{self.wp_path}',
'{self.backup_folder}')
"""
return add_new_website
# Key issue with deleting a website was to set the variable in single quotes. Otherwise error was present:
# The error was sqlite3.OperationalError: no such column: website_name.com
# Explicitly MySQL and Sqlite3 works with quotes for each element
#########################################################
#########################################################
######## DELETE WordPress WEBSITE ##############
#########################################################
#########################################################
def delete_wp_site(self):
delete_website = f"""
DELETE from wordpress_sites WHERE domain_name='{self.domain_name}';
"""
return delete_website
# Lists A awebsites selected on the command line with --action list_website
def show_site_data(self):
website_data = f"""
SELECT * FROM wordpress_sites WHERE domain_name='{self.domain_name}'
"""
return website_data
# Listing ALL websites that were added to the database
def list_all_websites(self):
list_website = """
select * from wordpress_sites;
"""
return list_website
class WordPressBackup:
def __init__(self):
self.username = args.user
self.password = args.password
self.hostname = args.host
self.wordpress_path = args.path
self.domain_name = args.domain
self.backup_folder = f'{self.domain_name}_backup_folder_{current_date}'
self.backup_tar_file = f"{self.backup_folder}/{self.domain_name}-backup-{current_date}.tar.gz"
self.database_backup_file = f"{self.backup_folder}/{self.domain_name}-backup-{current_date}.sql"
################ DATABASE CONNECTION FUNCTION ##############
def connect_to_host(self):
client = SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(self.hostname,port,self.username, self.password)
return f"Connection to {self.hostname} Was SuccessFull",client
#########################################################
######## CREATE BACKUP #############
#########################################################
def create_backup(self):
client = SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(self.hostname,port,self.username, self.password)
client.exec_command(f'mkdir {self.backup_folder}')
print("#"*50)
print('Backup Folder successfull created ')
print("#"*50)
print('Starting Creation of Database backup and Files Backup ')
print("#"*50)
print("...")
# RUN COMMAND SSH
############################ Backing up the wordpress database and files ###################
backup_wordpress = client.exec_command(f"wp --path={self.wordpress_path} db export {self.database_backup_file} && tar --exclude='{exclude_path}'-czf {self.backup_tar_file} -C {self.wordpress_path} .")
stdin, stdout, stderr = backup_wordpress
print("#"*50)
print(stdout.read().decode('utf-8'))
print("#"*50)
print(stderr.read().decode('utf-8'))
time.sleep(2)
print('Process of Backup finished successfully')
print("#"*50)
print()
print("Listing backup folder!")
print()
print("#"*50)
backup_folder_list = client.exec_command(f"ls -al {self.backup_folder}")
stdin , dir_list,stderr = backup_folder_list
print("#"*50)
print()
print(dir_list.read().decode('utf-8'))
print("#"*50)
return {"Connection":"Connection Successfulll",
"Folder":f"Backup Folder Created {self.backup_folder}"
} ,sys.exit('End of Program! Bye Bye')
#########################################################
#########################################################
######## CHECK BACKUP FOLDER #############
#########################################################
#########################################################
def check_backup_folder(self):
client = SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(self.hostname,port,self.username, self.password)
backup_folder_files = client.exec_command(f'ls {self.backup_folder}')
stdin ,stdout, stderr = backup_folder_files
output = stdout.read().decode('utf-8')
if stderr.read().decode('utf-8') != "":
client.exec_command(f'mkdir {self.backup_folder}')
print("#"*50)
print()
return "Backup Folder was created",stderr.read().decode('utf-8')
else:
print("#"*50)
print()
print("Backup Folder Already Exists:")
print(f"############## {self.backup_folder} ############## ")
print()
print('Listing Backup folder content')
print(f'{output}')
print("#"*50)
print()
return "End of script. Rerun the script to generate or restore a backup"
# return "Backup Was restored",stderr.read().decode('utf-8')
#########################################################
##########################################################
######## RESTORE BACKUP ###################
##########################################################
##########################################################
def restore_backup(self,):
client = SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(self.hostname,port,self.username, self.password)
################ DELETING THE WP CONTENT FOLDER ##################
delete_not_wp_content = client.exec_command(f"cd {self.wordpress_path}&&find . -mindepth 1 -maxdepth 1 ! -name 'wp-content' -delete")
stdin,stdout,stderr = delete_not_wp_content
print(f'Deleting files and folders from {self.wordpress_path}without wp-content')
print()
print(stdout.read().decode('utf-8'))
stdin.close()
print("DELETE FILES AND FOLDERS FROM wp-content withot uploads")
################ DELETING THE UPLOADS FOLDER ##################
delete_not_uploads = client.exec_command(f"cd {self.wordpress_path}/wp-content/&&find . -mindepth 1 -maxdepth 1 ! -name 'uploads' -delete")
i,o,e = delete_not_uploads
i.close()
print(o.read().decode('utf-8'))
print(f"Exporting the files from {self.backup_tar_file} to {self.wordpress_path}")
print(f"Exporting the files from {self.backup_tar_file} to {self.wordpress_path}")
restore_command = client.exec_command(f'tar -xzf {self.backup_tar_file} -C {self.wordpress_path}')
stdin ,stdout, stderr = restore_command
print(stdout.read().decode('utf-8'))
print("#"*50)
print('File restore completed! Continuing with database import')
print("#"*50)
print(f'Starting Database {self.database_backup_file} import process! ')
print("#"*50)
print("#"*50)
database_restore_command = client.exec_command(f'wp --path={self.wordpress_path} db import {self.database_backup_file}')
stdin ,stdout, stderr = database_restore_command
print(stdout.read().decode('utf-8'))
print("#"*50)
print()
print('Database Import Completed Successfully')
class BackupFromDatabase:
def __init__(self,username,password,hostname,wordpress_path,domain_name):
self.username = username
self.password = password
self.hostname = hostname
self.wordpress_path = wordpress_path
self.domain_name = domain_name
self.backup_folder = f'{self.domain_name}_backup_folder_{current_date}'
self.backup_tar_file = f"{self.backup_folder}/{self.domain_name}-backup-{current_date}.tar.gz"
self.database_backup_file = f"{self.backup_folder}/{self.domain_name}-backup-{current_date}.sql"
##########################################################
##########################################################
######## CREATE BACKUP #####################
##########################################################
##########################################################
def do_backup(self):
client = SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(self.hostname,port,self.username, self.password)
client.exec_command(f'mkdir {self.backup_folder}')
time.sleep(2)
print("#"*50)
print('Backup Folder successfull created ')
print("#"*50)
print('Starting Creation of Database backup and Files Backup ')
print("#"*50)
print("...")
# RUN COMMAND SSH
print("Excluding Uploads folder from, the backup")
print(exclude_path)
backup_wordpress = client.exec_command(f"wp --path={self.wordpress_path} db export {self.database_backup_file} && tar --exclude='{exclude_path}' --exclude-backups -czf {self.backup_tar_file} -C {self.wordpress_path} .")
stdin, stdout, stderr = backup_wordpress
print("#"*50)
print(stdout.read().decode('utf-8'))
print("#"*50)
print(stderr.read().decode('utf-8'))
time.sleep(2)
print('Process of Backup finished successfully')
print("#"*50)
print()
print("Listing backup folder!")
print()
print("#"*50)
backup_folder_list = client.exec_command(f"ls -al {self.backup_folder}")
stdin , dir_list,stderr = backup_folder_list
print("#"*50)
print()
print(dir_list.read().decode('utf-8'))
print("#"*50)
return {"Connection":"Connection Successfulll",
"Folder":f"Backup Folder Created {self.backup_folder}"
} ,sys.exit('End of Program! Bye Bye')
##########################################################
##########################################################
######## RESTORE BACKUP ###################
##########################################################
##########################################################
def restore_backup(self):
client = SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(self.hostname,port,self.username, self.password)
#delete_current_content = client.exec_command(f'rm -rf {self.wordpress_path}/*')
delete_not_wp_content = client.exec_command(f"cd {self.wordpress_path}&&find . -mindepth 1 -maxdepth 1 ! -name 'wp-content' -delete")
stdin,stdout,stderr = delete_not_wp_content
print(f'Deleting files and folders from {self.wordpress_path}without wp-content')
print()
print(stdout.read().decode('utf-8'))
stdin.close()
print("DELETE FILES AND FOLDERS FROM wp-content withot uploads")
delete_not_uploads = client.exec_command(f"cd {self.wordpress_path}/wp-content/&&find . -mindepth 1 -maxdepth 1 ! -name 'uploads' -delete")
i,o,e = delete_not_uploads
i.close()
print(o.read().decode('utf-8'))
########################### EXPORTING THE FILES FROM THE BACKUP ##################
print(f"Exporting the files from {self.backup_tar_file} to {self.wordpress_path}")
restore_command = client.exec_command(f"tar -xzf {self.backup_tar_file} -C {self.wordpress_path}")
stdin ,stdout, stderr = restore_command
print(stdout.read().decode('utf-8'))
print("#"*50)
print('File restore completed! Continuing with database import')
print("#"*50)
print(f'Starting Database {self.database_backup_file} import process! ')
print("#"*50)
print("#"*50)
database_restore_command = client.exec_command(f'wp --path={self.wordpress_path} db import {self.database_backup_file}')
stdin ,stdout, stderr = database_restore_command
print(stdout.read().decode('utf-8'))
print("#"*50)
print()
print('Database Import Completed Successfully')
if __name__ == "__main__":
# First Instance for main Actions backup,restore,check
main_backup = WordPressBackup()
# Secibd ubstance for utilizing the databases with the main class Variables
db_variables = WordPressBackup()
# db_instance Registers the website data into the database
db_instance = WpDatabase(db_variables.domain_name, db_variables.username, db_variables.password, db_variables.hostname, db_variables.wordpress_path, db_variables.backup_folder)
# Creating the Database cursor object
cursor = connection.cursor()
if args.action == 'restore':
print(main_backup.connect_to_host())
print(main_backup.restore_backup())
elif args.action == 'backup':
print("#"*50)
print(main_backup.create_backup())
elif args.action == 'add_website':
print("#"*50)
print(f'Website {db_variables.domain_name} was added successfully')
print("To list available websites run with --action list_website <website name> ")
cursor.execute(db_instance.add_website())
connection.commit()
connection.close()
elif args.action == 'delete_website':
print("#"*50)
print(f"Website -- {db_variables.domain_name} -- was deleted successfully")
cursor.execute(db_instance.delete_wp_site())
connection.commit()
connection.close()
elif args.action == 'list_website':
cursor.execute(db_instance.show_site_data())
site_data = cursor.fetchall()
wp_site_details = {'domain_name':site_data[0][1],
'username':site_data[0][2],
'password':site_data[0][3],
'hostname':site_data[0][4],
'wp_path':site_data[0][5],
'backup_folder':site_data[0][6],
}
pprint(OrderedDict(wp_site_details))
elif args.action == 'all_sites':
cursor.execute(db_instance.list_all_websites())
list_all_websites = cursor.fetchall()
for site in list_all_websites:
print(site)
connection.close()
elif args.action == 'list_website2':
cursor.execute(db_instance.show_site_data())
db_site_data = cursor.fetchall()
domain_name = db_site_data[0][1]
user = db_site_data[0][2]
password = db_site_data[0][3]
hostname = db_site_data[0][4]
wordpress_path = db_site_data[0][5]
print(f"Domain Name: {domain_name}")
print(f"SSH Username: {user}")
print(f"IP: {hostname}")
print(f"Path to WP installation: {wordpress_path}")
print(f"SSH Password: {password}")
elif args.action == "backup2":
cursor.execute(db_instance.show_site_data())
db_site_data = cursor.fetchall()
domain_name = db_site_data[0][1]
user = db_site_data[0][2]
password = db_site_data[0][3]
hostname = db_site_data[0][4]
wordpress_path = db_site_data[0][5]
backup_instance = BackupFromDatabase(user, password, hostname, wordpress_path, domain_name)
print(backup_instance.do_backup())
elif args.action == 'restore2':
cursor.execute(db_instance.show_site_data())
db_site_data = cursor.fetchall()
domain_name = db_site_data[0][1]
user = db_site_data[0][2]
password = db_site_data[0][3]
hostname = db_site_data[0][4]
wordpress_path = db_site_data[0][5]
backup_instance = BackupFromDatabase(user, password, hostname, wordpress_path, domain_name)
print(backup_instance.restore_backup())
else:
usage_function()
print(main_backup.check_backup_folder())