Automatic Backup MySQL Using Python

Here is a script I create to make backup MySQL Database. Check this out.


#!/usr/bin/env python
# PyBack.py v1.1
# MySQL Backup Script
# Author Andrey Ferriyan
# Package MySQL
# SubPackage MySQL Backup Script
# License GNU/GPL
# Description Backup MySQL With Cron Method


from ftplib import FTP
import subprocess
import tarfile


# User Database, Password Database, Host Database, Port Database
USERDB='andrey'
PASSDB='blablapass'
HOSTDB='localhost'
PORTDB='3306'


# Database pada mysql yang akan di backup
ARR_DB = ['wordpress']


# Hostname / IP Address, FTPLOGIN = user FTP, FTPPASS = password FTP
FTPHOST=''
FTPLOGIN=''
FTPPASS=''


class PyBack(object):
def __init__(self):
self.USERDB=USERDB
self.PASSDB=PASSDB
self.HOSTDB=HOSTDB
self.ARR_DB=ARR_DB
self.FTPHOST=FTPHOST
self.FTPLOGIN=FTPLOGIN
self.FTPPASS=FTPPASS
self.PORTDB=PORTDB


def backup(self):
subprocess.call("/bin/rm -rf /tmp/backup",shell=True)
subprocess.call("/bin/mkdir /tmp/backup",shell=True)


for x in self.ARR_DB:
subprocess.call("mysqldump -h "+self.HOSTDB+" --databases "+x+" --user="+self.USERDB+" --password="+self.PASSDB+" -P "+self.PORTDB+" -R > /tmp/backup/"+x+".sql",shell=True)


def grouping(self):
tar = tarfile.open("/tmp/backup.tar.bz2","w:bz2")
tar.add("/tmp/backup/")
tar.close()


def transfer(self):
ftp = FTP(self.FTPHOST)
ftp.login(self.FTPLOGIN,self.FTPPASS)
ftp.storbinary("STOR /tmp/backup.tar.bz2",open("/tmp/backup.tar.bz2","rb"),1024)


if __name__ == '__main__':
pyback = PyBack()
pyback.backup()
pyback.grouping()
pyback.transfer()

Carefull with Python Syntax, especially the indentation. You have to modify the script to match with your environment. Then you can install the script in the cron system. Just try it first, don’t forget to setup a FTP Server or a local FTP Server for testing it. Have a nice try!

7 Comments

  1. kalo liat2 sintaxnya phyton, sebenarnya cara kerja nya mirip sama php ato C, cuman dia syntaxnya mirip kayak basic, jadi lebih sederhana dan mudah dibaca….Mas itu programnya dhah pake API ya, manggil function pake PyBack v1.1

  2. @zuhry: PyBack itu sebenarnya kelas mas. Saya cuma pakai library bawaan dari python saja.

  3. oh iya dink, lali mas…..

  4. maaf mas, saya masih newbie gunain python…

    ketika dicoba syntax diatas muncul pesan seperti ini :
    expected an indented block (Script (Python), line 51)

    mungkin yang dimaksud = subprocess.call(“mysqldump -h “+self.HOSTDB+” –databases “+x+” –user=”+self.USERDB+” –password=”+self.PASSDB+” -P “+self.PORTDB+” -R > /tmp/backup/”+x+”.sql”,shell=True)

    mohon pencerahannya mas…
    sebelumnya makasih….

  5. Coba baris tersebut dijadikan satu baris dan jangan pindah ke baris dibawahnya.

  6. Itu nama file backupnya bisa urut berdasarkan date / time backup?

  7. belum tapi bisa di extend kalau mau. maaf baru cek blog lagi 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *