Скрипт для проверки и восстановления баз данных MySQL
Добавлено: 17 сен 2010, 14:36
Требует: Python 2.x и MySQLdb (mysql-модуль для Python, он же MySQL-python)
Код: Выделить всё
#!/usr/bin/env python
#########################################
# Check all tables in all mysql databases
#
# Written by Vladimir Rusinov <vladimir@greenmice.info>, http://greenmice.info/
#
# Reqirements:
# Python 2.x (tested with 2.4)
# MySQLdb
#########################################
# Settings:
host="localhost"
username="root"
password=""
exclude_dbs = ('information_schema', )
#########################################
# code
import sys
from optparse import OptionParser
import MySQLdb
parser = OptionParser()
parser.add_option("-f", "--fast", action="store_true", dest="fast",
default="False", help="use fast table ckeck")
(options, args) = parser.parse_args()
check_type=""
if options.fast:
check_type="FAST"
# first, get list of all databases:
try:
conn = MySQLdb.connect(host = host, user = username, passwd = password, db = "mysql")
cursor = conn.cursor()
cursor.execute("SHOW DATABASES")
dbs = cursor.fetchall()
#print dbs
conn.close()
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)
# now, check every database
for (db, ) in dbs:
if db in exclude_dbs:
continue
print "Checking database %s..." % (db, )
try:
conn = MySQLdb.connect(host = host, user = username, passwd = password, db = db)
cursor = conn.cursor()
cursor.execute("SHOW TABLES")
tables = cursor.fetchall()
for (table, ) in tables:
cursor.execute("CHECK TABLE `%s` %s" % (table, check_type))
status = cursor.fetchone()[3]
if status not in ['OK', 'Table is already up to date']:
print "Checking table %s.%s... %s; RUNNING REPAIR" % (db, table, status)
cursor.execute("REPAIR TABLE `%s`" % (table, ))
print cursor.fetchone()
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)