你是不是遇到过这样的问题?

1、一不小心,把刚安装的mysql root用户的密码忘记了。

2、根据网上很多教程修改后,还是提示ERROR 1045 (28000): Access denied for user ‘root’@'localhost’ (using password: YES) 。

3、一不小心,用root登陆mysql的时候,出现Access denied for user ‘root’@'localhost’ (using password: YES) 这样的错误。

如果碰巧你真的遇到上述问题,又或者是类似的问题,那么下面的这个脚本对你很适用!

 

把下面的内容,保存成reset_mysql_root_password.sh,然后修改相应的MySQL管理脚本,在/etc /init.d/mysql。mysql安装在/usr/local/mysql/他们的相应位置,最后执行sh reset_mysql_root_password.sh

#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

# Check if user is root
if [ $(id -u) != "0" ]; then
    printf "Error: You must be root to run this script!\n"
    exit 1
fi

echo "=========================================================================\n"
printf "Reset MySQL root Password! \n"
printf "Request Mysql management script must be /etc/init.d/mysql \n"
printf "And Mysql must be installed /usr/local/mysql/ \n"
printf "If not, please revise the appropriate location.
 \n"
printf "\n"
printf "=========================================================================\n"
printf "Usage: sh reset_mysql_root_password.sh\n"
printf "=========================================================================\n"

#Set mysql root password.

mysql_root_password=""
read -p "(Please input New MySQL root password):" mysql_root_password
if [ "$mysql_root_password" = "" ]; then
	echo "Error: Password can't be NULL!!\n"
	exit 1
fi

#Stoping MySQLd.
printf "Stoping MySQL...\n"
/etc/init.d/mysql stop

#Starting Mysqld_safe
printf "Starting MySQL with skip grant tables\n"
/usr/local/mysql/bin/mysqld_safe --skip-grant-tables >/dev/null 2>&1 &
printf "using mysql to flush privileges and reset password\n"
sleep 10

#Set Mysql root password
printf "update user set password = Password('$mysql_root_password') where User = 'root'\n"
/usr/local/mysql/bin/mysql -u root mysql << EOF
update user set password = Password('$mysql_root_password') where User = 'root';
EOF

#Check Password successfully orfailed
reset_status=`echo $?`
if [ $reset_status = "0" ]; then
printf "Password reset succesfully. Now killing mysqld softly\n"
killall mysqld
sleep 10
	#Restarting mysqld
printf "Restarting the actual mysql service\n"
/etc/init.d/mysql start
printf "Password successfully reset to '$mysql_root_password'\n"
else
printf "Reset MySQL root password failed!\n"
fi