欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

一键重置mysql的root密码脚本

程序员文章站 2024-03-31 16:45:10
@echo off title mysql ::从注册表找到mysql的安装路径写入文件mysql.txt reg query hklm\sy...
 @echo off 

title mysql 

::从注册表找到mysql的安装路径写入文件mysql.txt 
reg query hklm\system\controlset001\services\mysql | find /i "imagepath">c:\mysql.txt 
if %errorlevel% neq 0 ( 
echo mysql not found 
pause 
exit 
) 

::以”为分隔符,截取第二段内容保存到变量mysqlpath 
for /f tokens^=2^ delims^=^" %%i in (c:\mysql.txt) do set mysqlpath=%%i 
del c:\mysql.txt /f 

::路径中/替换为\ 
set mysqlpath=%mysqlpath:/=\% 

::删除路径最后一个字符(该字符不可见,可能是回车换行之类的) 
set mysqlpath=%mysqlpath:~0,-1% 

:backtomain 

::取得路径最后一个字符看等不等于\ 
set character=%mysqlpath:~-1,1% 

::如果最后一个字符不等于\,那么跳转到getpath删除mysqlpath的最后一个字符 
if not %character% == \ goto getpath 

::进入mysql安装路径c:\program files\mysql\mysql server 5.0\bin 
cd /d "%mysqlpath%" 

::echo %mysqlpath% 

if %errorlevel% neq 0 ( 
echo mysql not found 
pause 
exit 
) 

::禁用mysql服务,跳过权限验证修改密码 
taskkill /f /im mysqld-nt.exe 
net stop mysql >nul 
start /b mysqld-nt --skip-grant-tables 
ping -n 2 127.0.0.1 >nul 
echo use mysql >c:\config.tmp 
echo update user set password=password("") where user="root";>>c:\config.tmp 
echo flush privileges; >>c:\config.tmp 
echo exit >>c:\config.tmp 

::因为是交互式,所以从文件读取内容 
mysql <c:\config.tmp 
taskkill /f /im mysqld-nt.exe 
net stop mysql >nul 
net start mysql 
del c:\config.tmp /f 
pause 
exit 

::删除路径最后一个字符,跳回主程序 
:getpath 
set mysqlpath=%mysqlpath:~0,-1% 
goto backtomain

如果是用wamp一键安装需要改一些脚本,主要是注册表搜索路径改变,返回值改变,服务名改变了,mysql安装路径变成d:\wamp\bin\mysql\mysql5.5.24\bin,少了mysqld-nt这个东西,进程里面也没有mysqld-nt.exe

@echo off 

title mysql 

reg query hklm\system\controlset001\services\wampmysqld | find /i "imagepath">c:\mysql.txt 

if %errorlevel% neq 0 ( 
echo mysql not found 
pause 
exit 
) 

for /f "tokens=3 delims= " %%i in (c:\mysql.txt) do set mysqlpath=%%i 
del c:\mysql.txt /f 
set mysqlpath=%mysqlpath:/=\% 
set mysqlpath=%mysqlpath:~0,-1% 

:backtomain 
set character=%mysqlpath:~-1,1% 
if not %character% == \ goto getpath 
cd /d "%mysqlpath%" 

::echo %mysqlpath% 

if %errorlevel% neq 0 ( 
echo mysql not found 
pause 
exit 
) 

taskkill /f /im mysqld.exe 
net stop wampmysqld >nul 
start /b mysqld -nt --skip-grant-tables 
ping -n 2 127.0.0.1 >nul 
echo use mysql >c:\config.tmp 
echo update user set password=password("") where user="root";>>c:\config.tmp 
echo flush privileges; >>c:\config.tmp 
echo exit >>c:\config.tmp 

mysql <c:\config.tmp 

taskkill /f /im mysqld.exe 
net stop wampmysqld >nul 
net start wampmysqld 
del c:\config.tmp /f 

pause 
exit 

:getpath 
set mysqlpath=%mysqlpath:~0,-1% 
goto backtomain