2017-08-31 155 views
1

我有一个小批量脚本从mysql.err文件获取临时密码。包含完整字符串分隔符的提取字符串

但我有一个问题,当一个密码包含:是在分隔符匹配使用导致密码不会得到原样..

是否有任何其他的方法来得到正确的密码?

@echo off 

setlocal enableextensions enabledelayedexpansion 

set mysql_dir=C:\database\mysql 

echo. 
echo. 
echo Search For Current MySQL Password 
FOR /F "tokens=4 delims=:" %%G in ('find /I "A temporary password is generated for [email protected]:" ^<%mysql_dir%\data\%ComputerName%.err') DO set temp_mysql_password="%%G" 

echo. 
echo. 
echo Current MySQL password: %temp_mysql_password% 

mysql.err文件内容是:

2017-08-31T07:38:36.195916Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened. 
2017-08-31T07:38:36.205943Z 22 [Note] A temporary password is generated for [email protected]: v>dqu;;&)7:Y 
2017-08-31T07:38:42.510215Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details). 

而问题是,密码
v>dqu;;&)7:Y **包含已:将被提取为:
v>dqu;;&)7

回答

1

这样无定界符它会工作:

... 
for /F "delims=" %%G in ('find /I "A temporary password is generated for" ^<%mysql_dir%\data\%ComputerName%.err') do (
    set "temp_mysql_password=%%G" 
    set "temp_mysql_password=!temp_mysql_password:*A temporary password is generated for [email protected]: =!" 
) 


echo. 
echo. 
rem Note the ! around the variable 
echo Current MySQL password: !temp_mysql_password! 

它使用说明here: Remove - Remove a substring using string substitution字符串操作。

请注意,它仅适用于[email protected],因为该字符串是搜索替换字符串的一部分。

,使之成为任何[email protected]组合,你必须使用3个字符串替换,而不是一个工作:

set "temp_mysql_password=!temp_mysql_password:*A temporary password is generated for =!" 
set "temp_mysql_password=!temp_mysql_password:*@=!" 
set "temp_mysql_password=!temp_mysql_password:*: =!" 

输出:

Current MySQL password: v>dqu;;&)7:Y 

如果一定要使用您的解决方案(使用tokensdelims)您可以连接所有分隔的部分,请参阅here on SO how it works

+0

谢谢你的时间!它是否按预期工作。不错的见解! – oriceon

2

如果您使用过“tokens = 3 * delims =:”,而下一个变量为%% H,您将获得未解析的密码。
星号表示输入的其余部分,不用在分隔符处进一步分割。

@echo off & setlocal enableextensions enabledelayedexpansion 
set mysql_dir=C:\database\mysql 
echo. 
echo. 
echo Search For Current MySQL Password 
FOR /F "tokens=3* delims=:" %%G in (
    'find /I "A temporary password is generated for [email protected]:" ^<%mysql_dir%\data\%ComputerName%.err' 
) DO set "temp_mysql_password=%%H" 
set "temp_mysql_password=%temp_mysql_password:~1%" 
echo. 
echo. 
echo Current MySQL password: %temp_mysql_password% 
+0

密码将为:'“v> dqu ;;&)7:Y”'(带引号)。使用以下命令测试它:'回显当前的MySQL密码:^ <%temp_mysql_password%^>'。但是,即使set命令(导致引号)是正确的:'set'temp_mysql_password = %% H“'它将以开始的空格开始。好的,这可以很容易地删除,所以这是一个很好的答案后的更正。请注意,它只适用于:'root @ localhost'。 –

+0

@AndreKampling同意,我没有彻底修改代码。改变。 – LotPings

+0

适用于每个用户,当更改搜索字符串为“”时生成临时密码“ – Stephan