Created
April 23, 2014 21:55
-
-
Save James1x0/11233788 to your computer and use it in GitHub Desktop.
Python Mongodb Backup to use sftp and sendmail to alert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# import modules used here | |
import zipfile | |
import os | |
import shutil | |
import sys | |
import subprocess | |
import datetime | |
import pysftp as sftp | |
import re | |
from email.mime.text import MIMEText | |
def doBackup(): | |
db = sys.argv[1] | |
print "Getting ready to backup db", db + "..." | |
dumpPath = os.path.abspath("tmp_dmp") | |
if not os.path.exists(dumpPath): os.makedirs(dumpPath) | |
backup_log = subprocess.Popen(['mongodump -o ' + dumpPath + ' -d' + db], stdout=subprocess.PIPE, shell=True).communicate()[0] | |
print "Dumped via shell, zipping..." | |
zipName = "MongoDump_" + str(datetime.datetime.now()) | |
zipDir(zipName, dumpPath) | |
print "Zipped. Now transferring..." | |
try: | |
connection = sftp.Connection(host="0.0.0.0", username="example", password="example") | |
szip = re.sub(':', '-', zipName + ".zip") | |
print "Storing", szip, "on remote server..." | |
connection.put("/" + zipName + ".zip", szip) | |
connection.close() | |
print "Completed transfer!" | |
msg = MIMEText("Completed backup of " + sys.argv[1] + " mongo db @ " + str(datetime.datetime.now()) + ".\r\nNo further action is required.") | |
msg["From"] = "[email protected]" | |
msg["To"] = "[email protected]" | |
msg["Subject"] = "Successful Backup" | |
p = subprocess.Popen(["/usr/sbin/sendmail", "-t"], stdin=subprocess.PIPE).communicate(msg.as_string()) | |
except Exception, e: | |
print str(e) | |
msg = MIMEText("Failed to store backup.\r\nERR: " + str(e)) | |
msg["From"] = "[email protected]" | |
msg["To"] = "[email protected]" | |
msg["Subject"] = "Failed Backup" | |
p = subprocess.Popen(["/usr/sbin/sendmail", "-t"], stdin=subprocess.PIPE).communicate(msg.as_string()) | |
cleanUp(zipName, dumpPath) | |
def cleanUp(z, d): | |
print "Cleaning up..." | |
os.remove(os.path.abspath(z + ".zip")) | |
shutil.rmtree(d) | |
def zipDir(foldername, target_dir): | |
zipobj = zipfile.ZipFile(foldername + '.zip', 'w', zipfile.ZIP_DEFLATED) | |
rootlen = len(target_dir) + 1 | |
for base, dirs, files in os.walk(target_dir): | |
for file in files: | |
fn = os.path.join(base, file) | |
zipobj.write(fn, fn[rootlen:]) | |
if __name__ == '__main__': | |
doBackup() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment