-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrun.py
58 lines (53 loc) · 1.94 KB
/
run.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
#!/usr/bin/python
import os, sys, datetime, tarfile, os.path
from pymongo import MongoClient
from bson.json_util import dumps
def create_folder_backup(dbname):
dt = datetime.datetime.now()
directory = (f'backups/bk_{dbname}_{dt.month}-{dt.day}-{dt.year}__{dt.hour}_{dt.minute}')
if not os.path.exists(directory):
os.makedirs(directory)
return directory
def run_backup(mongoUri, dbname):
client = MongoClient(mongoUri)
db = client[dbname]
collections = db.list_collection_names()
files_to_compress = []
directory = create_folder_backup(dbname)
for collection in collections:
db_collection = db[collection]
cursor = db_collection.find({})
filename = (f'{directory}/{collection}.json')
files_to_compress.append(filename)
with open(filename, 'w') as file:
file.write('[')
for document in cursor:
file.write(dumps(document))
file.write(',')
file.write(']')
tar_file = (f'{directory}.tar.gz')
make_tarfile(tar_file,files_to_compress)
def make_tarfile(output_filename, source_dir):
tar = tarfile.open(output_filename, "w:gz")
for filename in source_dir:
tar.add(filename)
tar.close()
if __name__ == '__main__':
if (not(len(sys.argv) == 6)):
print('[-] Incorrect number of arguments')
print('python run.py [username] [password] [host] [port] [dbname]')
exit()
else:
username = sys.argv[1]
password = sys.argv[2]
host = sys.argv[3]
port = sys.argv[4]
dbname = sys.argv[5]
mongoUri = (f'mongodb://{username}:{password}@{host}:{port}/{dbname}?authSource=admin')
try:
run_backup(mongoUri, dbname)
print('[*] Successfully performed backup')
except Exception as e:
print('[-] An unexpected error has occurred')
print('[-] '+ str(e) )
print('[-] EXIT')