Archive for December, 2008

Backup dreamhost database

Tuesday, December 16th, 2008

Just wanted to quickly share my database backup script with the world, and mostly with myself, since I tend to forget those things. Goal is to backup my database, zip the backup file and mail it to a google apps mail account that accompanies my domain.

I used python for this script, it’s been a long while since I did any python, but I still remember why I liked it so much. Anyway, here is the script.

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
#!/usr/bin/python
 
import os
from time import gmtime, strftime
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
 
gmail_user = "admin@domain.com"
gmail_pwd = "passwd"
backup_user = "admin@domain.com"
dbUser = "dbuser"
dbPasswd = "dbpasswd"
dbHost = "mysql.domain.com"
dbName = "my_dear_database"
 
 
def mail(to, subject, text, attach):
   msg = MIMEMultipart()
 
   msg['From'] = gmail_user
   msg['To'] = to
   msg['Subject'] = subject
 
   msg.attach(MIMEText(text))
 
   part = MIMEBase('application', 'octet-stream')
   part.set_payload(open(attach, 'rb').read())
   Encoders.encode_base64(part)
   part.add_header('Content-Disposition',
           'attachment; filename="%s"' % os.path.basename(attach))
   msg.attach(part)
 
   mailServer = smtplib.SMTP("smtp.gmail.com", 587)
   mailServer.ehlo()
   mailServer.starttls()
   mailServer.ehlo()
   mailServer.login(gmail_user, gmail_pwd)
   mailServer.sendmail(gmail_user, to, msg.as_string())
   # Should be mailServer.quit(), but that crashes...
   mailServer.close()
 
 
 
def dumpDb():
    backupFile = "dbbackup.%s.sql.gz" % strftime("%Y%m%d-%H:%M:%S", gmtime())
    os.system("""mysqldump -u%s -p%s -h %s %s|gzip > %s""" % (dbUser, dbPasswd, dbHost, dbName, backupFile))
    return backupFile
 
def mailBackup(fileName):
    mail(backup_user,
   "[Backup] Backup of %s" % strftime("%Y %m %d-%H:%M", gmtime()),
   "Backup of database in attachement",
    fileName)
 
 
def doBackup():
    mailBackup(dumpDb())
 
if __name__ == "__main__":
    doBackup()

I then installed a cron job to run this script each night.

With a lot of thanks to this post for inspiration on how to send mail with attachments through gmail.

Anyone additional thoughts on backing up a dreamhost account? Please share those in the comments. Thanks!