2017-08-31 141 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

相關問題