Afrafre

误删root用户,如何恢复

1.修改配置文件,获取权限登录
root@localhost#vi /etc/my,cnf
添加:skip-grant-tables
root@localhost#systemctl restart mysqld
2.登录创建root用户
root@localhost#mysql
mysql>use mysql;

 insert into user set user=\'root\',ssl_cipher=\'\',x509_issuer=\'\',x509_subject=\'\';
3.更新root用户权限
update user set Host=‘localhost’,select_priv=‘y’, insert_priv=‘y’,update_priv=‘y’,Alter_priv=‘y’,delete_priv=‘y’,create_priv=‘y’,drop_priv=‘y’,reload_priv=‘y’,shutdown_priv=‘y’,Process_priv=‘y’,file_priv=‘y’,grant_priv=‘y’,References_priv=‘y’,index_priv=‘y’,create_user_priv=‘y’,show_db_priv=‘y’,super_priv=‘y’,create_tmp_table_priv=‘y’,Lock_tables_priv=‘y’,execute_priv=‘y’,repl_slave_priv=‘y’,repl_client_priv=‘y’,create_view_priv=‘y’,show_view_priv=‘y’,create_routine_priv=‘y’,alter_routine_priv=‘y’,create_user_priv=‘y’ where user=‘root’;
4.修改配置文件权限
将1中的–skip-grant-tables删除
root@localhost#systemctl restart mysqld
root@localhost#mysql -uroot -p
password: -----密码为空
5.修改密码
mysql>use mysql;
使用命令更改root密码:
UPDATE user SET Password=PASSWORD(\'root\') where USER=\'root\';
刷新权限:
FLUSH PRIVILEGES;
然后退出,重新登录: 
quit

方法二:Python 脚本

import pymysql
import os
#修改配置文件获取权限
print("modify my.cnf skip grant tables.........")
os.system("echo\'-skip-grant-tables\'>>/etc/my.cnf")
k = os.system("systemctl restart mysqld")
if k==0:
    pint("erro:",k)
else:
    print("modify success!")
    #连接数据库
    db=pymysql.connect("127.0.0.1")
    cursor=db.cursor()
    cursor.execute("use mysql")

    #添加root用户并更新root权限
    SQL_SYN="insert into user(User,authentication_string,ssl_cipher x509_issuer x509_subject) values(\'root\',\'\',\'\',\'\',\'\')"
    cursor.execute(SQL_SYN)
    SQL_SYN="update user set Host=\'%\',select_priv=\'y\', insert_priv=\'y\',update_priv=\'y\',Alter_priv=\'y\',delete_priv=\'y\',create_priv=\'y\',drop_priv=\'y\',reload_priv=\'y\',shutdown_priv=\'y\',Process_priv=\'y\',file_priv=\'y\',grant_priv=\'y\',References_priv=\'y\',index_priv=\'y\',create_user_priv=\'y\',show_db_priv=\'y\',super_priv=\'y\',create_tmp_table_priv=\'y\',Lock_tables_priv=\'y\',execute_priv=\'y\',repl_slave_priv=\'y\',repl_client_priv=\'y\',create_view_priv=\'y\',show_view_priv=\'y\',create_routine_priv=\'y\',alter_routine_priv=\'y\',create_user_priv=\'y\' where user=\'root\'"
    cursor.execute(SQL_SYN)
    db.close()

    #修改配置文件取消权限
    os.system("sed -i \'/-skip-grant/d\' /etc/my.cnf")
    print("modify my.cnf skip grant tables.........")
    k=os.system("systemctl restart mysqld")
    if k!=0:
        print("erro:",k)
    else:
        print("modify success!")
        db = pymysql.connect("127.0.0.1","root","","mysql")
        #修改密码
        SQL_SYN="alter user \'root\'@\'%\' identified with mysql_native_password by \'Admin@123\'"
        db.cursor(SQL_SYN)
        #权限设置
        SQL_SYN="grant all privileges on *.* to \'root\'@\'%\'"
        db.cursor(SQL_SYN)
        db.close()
        print("root user adding success!! The password of \'root\' is \'Admin@123\'")

分类:

技术点:

相关文章: