#! /usr/bin/python ## # Copyright (C) 2023, Oracle and/or its affiliates. All rights reserved. ## ## # \file restore_mysqluser.py # \brief This is a runnable Python file that will take backup of custom mysql user and restoring it after sds upgrade. # # # # \author $Author$ # \date $Date$ # \par Additional Details: # # \par Revision History: . Revision history # \verbatim # # \endverbatim import warnings import sys, os import time import subprocess from os import remove from datetime import datetime import datetime from inspect import currentframe start = time.time() ENABLE_SCRIPT_PRINTS = 0 SUBSCRIBER_OBJ = {} get_time = str(datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")) LOG_FILE_NAME = "log_create_sql_" + get_time + ".txt" SQL_FILE_NAME = "USER_COMMANDS_" + get_time + ".sql" DUMP_FILE_NAME = "DUMP_COMMANDS_" + get_time + ".sql" USER_FILE_NAME = "user_" + get_time + ".txt" """ Function to get line number """ def GetLineNumber(): cf = currentframe() return cf.f_back.f_lineno """ Function to write log """ def WriteAndLogFile(output_string, line_num): output_string = "[" + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + ", " + "LINE NO : " + str(line_num) + "] " + output_string if ENABLE_SCRIPT_PRINTS: sys.stdout.write(output_string) try: log_file.write(output_string) except: return """Function to print Help Guide""" def PrintHelpGuide(): sys.stdout.write("|******************************* HELP GUIDE ***********************************|\n") sys.stdout.write("|The script creates the .sql file and expects sds tool o/p file as an argument |\n") sys.stdout.write("|pass sds tool o/p as input file to script |\n") sys.stdout.write("|******************************* Options Support ******************************|\n") sys.stdout.write("|--------> 1. --verbose or --v or --V |\n") sys.stdout.write("|--------> 2. --clean (Deletes the old log and .sql files) |\n") sys.stdout.write("|For example : python create_sql_data.py sds_log.txt --options ..... |\n") sys.stdout.write("|******************************************************************************|\n") """ This function creates the log file for the script """ def CreateLogFile(): global log_file try: log_file = open(LOG_FILE_NAME, "w") except: sys.stdout.write("Unable to create " + LOG_FILE_NAME) sys.exit() """ This function clears the old logs """ def CleanLogFiles(): del_file = "log_create_sql" for counter in range(4): if counter == 1: del_file = "USER_COMMANDS" if counter == 2: del_file = "user_" if counter == 3: del_file = "DUMP_COMMANDS" cmd = "ls " + del_file + "*" output = os.popen(cmd + " 2> /dev/null").read() DATA = output.split("\n") for file_name in DATA: cmd = "rm " + file_name output = os.popen(cmd + " 2> /dev/null").read() """ This function checks the input agrument passed to the script """ def CheckInputArguments(argv): global ENABLE_SCRIPT_PRINTS FILE_NAME = "" """ This function is checking the arguments passed to the script and store the data """ argument_count = len(argv) for counter in range(argument_count): if sys.argv[counter] == "--help" or sys.argv[counter] == "--h" or sys.argv[counter] == "--H" or sys.argv[counter] == "--HELP": PrintHelpGuide() sys.exit() if sys.argv[counter] == "--verbose" or sys.argv[counter] == "--v" or sys.argv[counter] == "--V": ENABLE_SCRIPT_PRINTS = 1 continue if sys.argv[counter] == "--clean": CleanLogFiles() CloseFileEndScript(True) FILE_NAME = sys.argv[counter] CreateLogFile() WriteAndLogFile("LOG_FILE_NAME : " + LOG_FILE_NAME + '\n', GetLineNumber()) return FILE_NAME; """ This function close the script file """ def CloseFileEndScript(exit_script): end = time.time() sys.stdout.write("Execution Time : "+ str((end-start)/60) + " mins" + "\n") WriteAndLogFile("Execution Time : "+ str((end-start)/60) + " mins" + "\n", GetLineNumber()) WriteAndLogFile("Script Finished\n", GetLineNumber()) try: if log_file.closed == False: log_file.close() if shell_file.closed == False: sql.closed() except: try: if shell_file.closed == False: sql.close() except: if exit_script: sys.stdout.write("\033[0;37mScript Finished !!\n") sys.exit() if exit_script: sys.stdout.write("\033[0;37mScript Finished !!\n") sys.exit() if exit_script: sys.stdout.write("\033[0;37mScript Finished !!\n") sys.exit() def CreateUserFile(): global user_file try: user_file = open(USER_FILE_NAME, "w") sys.stdout.write("\033[1;32mUSER File : "+ USER_FILE_NAME + "\n") except: WriteAndLogFile("Unable to create "+ USER_FILE_NAME + "\n", GetLineNumber()) CloseFileEndScript(True) def FetchCustomUser(): CreateUserFile() WriteAndLogFile("Inside : " + 'FetchCustomUser()\n', GetLineNumber()) cmd = "rm temp.sql" output_file = os.popen(cmd + " 2> /dev/null").read() temp_file = open("temp.sql", "w") temp_file.write("use mysql;\n") sql_string = "select user from user;\n" temp_file.write(sql_string) WriteAndLogFile("SQL Command : " + sql_string +'\n', GetLineNumber()) temp_file.close() cmd = "sudo Imysql.client -uroot -pImysql23root < temp.sql" output_file = os.popen(cmd + " 2> /dev/null").readlines() if len(output_file) > 0: #OUTPUT_LIST = output_file.split("\n") user_file.writelines(output_file[1:]) cmd = "rm temp.sql" output_file = os.popen(cmd + " 2> /dev/null").read() user_file.close() else: WriteAndLogFile("SQL Command O/P : " +'-1\n', GetLineNumber()) cmd = "rm temp.sql" output_file = os.popen(cmd + " 2> /dev/null").read() return "-1" def CreateSqldump(data): WriteAndLogFile("Input Data : " + data, GetLineNumber()) WriteAndLogFile("USER : " + data + '\n', GetLineNumber()) log_command_data = "" log_command_data = "" sql_data = "" sql_data = "flush privileges" + ";\n" sql_file.write(sql_data) log_command_data += sql_data sql_data = "GRANT SELECT ON sds.Msisdn TO \'" + data + "\';\n" sql_file.write(sql_data) log_command_data += sql_data sql_data = "GRANT SELECT ON sds.Imsi TO \'" + data + "\';\n" sql_file.write(sql_data) log_command_data += sql_data sql_data = "GRANT SELECT ON sds.NaiUser TO \'" + data + "\';\n" sql_file.write(sql_data) log_command_data += sql_data sql_data = "GRANT SELECT ON sds.WildcardNaiUser TO \'" + data + "\';\n" sql_file.write(sql_data) log_command_data += sql_data sql_data = "GRANT SELECT ON sds.NaiHost TO \'" + data + "\';\n" sql_file.write(sql_data) log_command_data += sql_data sql_data = "GRANT SELECT ON sds.Destination TO \'" + data + "\';\n" sql_file.write(sql_data) log_command_data += sql_data sql_data = "GRANT SELECT ON sds.DestinationMap TO \'" + data + "\';\n" sql_file.write(sql_data) log_command_data += sql_data sql_data = "GRANT SELECT ON sds.Subscriber TO \'" + data + "\';\n" sql_file.write(sql_data) log_command_data += sql_data sql_data = "GRANT SELECT ON sds.AccountToSubscriber TO \'" + data + "\';\n" sql_file.write(sql_data) log_command_data += sql_data sql_data = "GRANT SELECT ON sds.MsisdnToSubscriber TO \'" + data + "\';\n" sql_file.write(sql_data) log_command_data += sql_data sql_data = "GRANT SELECT ON sds.ImsiToSubscriber TO \'" + data + "\';\n" sql_file.write(sql_data) log_command_data += sql_data WriteAndLogFile("Commands for the Input Data\n" + log_command_data,GetLineNumber()) def CreateSqlFile(): global sql_file try: sql_file = open(SQL_FILE_NAME, "w") sys.stdout.write("\033[1;32mSQL PERMISSION File : "+ SQL_FILE_NAME + "\n") except: WriteAndLogFile("Unable to create "+ SQL_FILE_NAME + "\n", GetLineNumber()) CloseFileEndScript(True) def CreateDbDump(): cmd = "export MYSQL_PWD='Imysql23root';Imysqldump -uroot mysql user > " + DUMP_FILE_NAME output = os.system(cmd) warnings.simplefilter('ignore') sys.stdout.write("\033[1;32mDUMP File : "+ DUMP_FILE_NAME + "\n") def AppendSqlData(): #opening DUMP_FILE_NAME in append mode and SQL_FILE_NAME file in read mode f1 = open(DUMP_FILE_NAME, 'a+') f2 = open(SQL_FILE_NAME, 'r') #appending the contents of the file f1.write(f2.read()) # relocating the cursor of the files at the beginning f1.seek(0) f2.seek(0) # closing the files f1.close() f2.close() if __name__ == "__main__": if len(sys.argv) < 1: sys.stdout.write("\033[4;31mError : Invalid argument count !!\n") sys.stdout.write("\033[4;31mError : Run ./create_sql_data.py --help!!\n") CloseFileEndScript(True) CheckInputArguments(sys.argv) FetchCustomUser() sys.stdout.write("\033[1;32mLog File : "+ LOG_FILE_NAME + "\n") try: file_sql = open(USER_FILE_NAME, 'r') except: WriteAndLogFile("unable to open : " + input_file_name + '\n', GetLineNumber()) sys.stdout.write("Unable to open " + input_file_name + "\n") sys.stdout.write("\033[4;31mRun ./create_sql_data.py --help!!\n") CloseFileEndScript(True) create_sql_file = 0 while True: line = file_sql.readline() if not line: break LIST = line.split(" ") data = LIST[0].strip() if data !='awadmin' and data !='root' and data !='mysql.infoschema' and data !='mysql.session' and data != 'mysql.sys' and data !='qsuser' and data !='qsadmin': if create_sql_file == 0: CreateSqlFile(); create_sql_file = 1 CreateSqldump(data); CreateDbDump(); try: user_file.close() except: sys.stdout.write("Unable to close !!" + "\n") try: sql_file.close() except: sys.stdout.write("No custom user present in mysql user table !!" + "\n") exit(0) AppendSqlData() CloseFileEndScript(True)