how to write a bash script which will dump a database and restore it. there should be two arguments. first one is the name of db which is going to be dumped and another one is name of the db in which i am going to restore the previously dump data.
-
I wrote a BASH script that did this once, but I found it to be difficult to maintain on account of the subtleties of BASH scripting. I recommend you do what I did and consider moving to a python implementation, or perhaps looking into database replication.Chris– Chris2010-07-26 15:47:10 +00:00Commented Jul 26, 2010 at 15:47
Add a comment
|
2 Answers
I got a python script who take the dump and upload it to s3. I think its better than bash script:
import datetime
import subprocess, tarfile, os, S3, tempfile
#Mysql
MYSQL_USER = "xxxx"
MYSQL_PASS = "xxx"
MYSQL_DB = "xxxxx"
MYSQL_HOST = "localhost"
MYSQL_DUMP = "mysqldump"
AWS_ACCESS_KEY_ID = "xxxxxxxxxxxx"
AWS_SECRET_ACCESS_KEY = "yyyyyyyyyyyyyyyyyyyy"
BUCKET_NAME = "bucket"
FOLDER = "backup/"
KEEP = 5
EXT_TIME = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%dT%H:%M')
print "start mysqldump..."
proc1 = subprocess.Popen(MYSQL_DUMP + " --no-create-info -u %s -p%s -x --databases %s" % (MYSQL_USER, MYSQL_PASS, MYSQL_DB), shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
t1 = tempfile.NamedTemporaryFile()
t1.write(proc1.communicate()[0])
tar = tarfile.open( (os.path.join(os.curdir, MYSQL_DB + "_%s.tar.gz" % (EXT_TIME))), "w|gz")
tar.add(t1.name, MYSQL_DB + "_data.sql")
t1.close()
tar.close()
print "uploading to S3..."
conn = S3.AWSAuthConnection( AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY )
tardata = open(os.path.join(os.curdir, MYSQL_DB + "_%s.tar.gz" % EXT_TIME) , "rb").read()
response = conn.put(BUCKET_NAME, FOLDER + MYSQL_DB + "_%s.tar.gz" % EXT_TIME, S3.S3Object(tardata))
if response.http_response.status == 200 :
print "sucessfully uploaded the archive to Amazon S3"
else:
print "Uploading database dump to Amazon S3 is not successful"
os.remove(os.path.join(os.curdir, MYSQL_DB + "_%s.tar.gz" % (EXT_TIME)))
3 Comments
Jeevan Dongre
I am getting an error when I was trying this code in my machine.conn = S3.AWSAuthConnection( AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY ) AttributeError: 'module' object has no attribute 'AWSAuthConnection'
Tauquir
You will get S3.py aws.amazon.com/code/134. Download and you will find S3.py file under python folder.
jrswgtr
You ask "how to write a bash script". How can a Python script be the accepted and most up voted answer?