#!/usr/bin/env python import MySQLdb import ConfigParser import sys import os MYSQL_DATABASE_NAME="moodle" MYSQL_DBUSER_NAME="moodle" MYSQL_DBUSER_PASSWD="moodle" class MySQLManager: def __init__(self): self.readPassword() self.connect() #def __init__ def readPassword(self): try: config = ConfigParser.ConfigParser() config.read('/root/.my.cnf') self.user = config.get("mysql","user") self.password= config.get("mysql","password") except: print "[!] .my.cnf file not found [!]" sys.exit(1) #def readPassword def connect(self): try: self.connection=MySQLdb.connect(host="localhost",user=self.user,passwd=self.password) except: print "[!] Error connecting to MySQL [!]" sys.exit(1) #def connect def createDB(self,moodle_pass): sql=[] sql.append("CREATE DATABASE " + MYSQL_DATABASE_NAME + " CHARACTER SET utf8 COLLATE utf8_general_ci") sql.append("DROP USER " + MYSQL_DBUSER_NAME) sql.append("FLUSH PRIVILEGES") sql.append("CREATE USER " + MYSQL_DBUSER_NAME + " IDENTIFIED BY '" + moodle_pass + "'") sql.append("GRANT ALL PRIVILEGES ON " + MYSQL_DATABASE_NAME +".* TO " + MYSQL_DBUSER_NAME +"@localhost IDENTIFIED BY '" + moodle_pass + "'") sql.append("FLUSH PRIVILEGES") for query in sql: try: print "Executing " + query cursor = self.connection.cursor() cursor.execute(query) cursor.close() except Exception as e: print e #def createDB def dropDB(self): sql=[] sql.append("DROP DATABASE " + MYSQL_DATABASE_NAME ) sql.append("DROP USER " + MYSQL_DBUSER_NAME ) sql.append("FLUSH PRIVILEGES") for query in sql: try: print "Executing " + query cursor = self.connection.cursor() cursor.execute(query) cursor.close() except Exception as e: print e #def dropDB def checkDB(self): try: print "Checking moodle DB..." self.connection=MySQLdb.connect(host="localhost",user=self.user,passwd=self.password,db=MYSQL_DATABASE_NAME) cursor = self.connection.cursor() cursor.execute("show tables") x=cursor.fetchall() if len(x) > 0 : print "It contains tables" sys.exit(0) else: print "Moodle DB is empty" sys.exit(1) except Exception as e: print e sys.exit(1) #def checkDB #class MySQLManager def usage(): print "USAGE:" print "\tmysql_moodle {create MOODLE_PASSWORD | delete | check_tables }" #def usage if __name__=="__main__": if len(sys.argv)<2: usage() sys.exit(1) '''if os.getenv("USER")!="root": print "You need superuser privileges" sys.exit(1) ''' mysql=MySQLManager() if sys.argv[1]=="create": if len(sys.argv)>2: mysql.createDB(sys.argv[2]) sys.exit(0) else: usage() sys.exit(1) elif sys.argv[1]=="delete": mysql.dropDB() sys.exit(0) elif sys.argv[1]=="check_tables": mysql.checkDB() sys.exit(0) else: usage()