Make a random string in batch

2019-06-01 03:24发布

问题:

I am trying to make a random string in batch, and I have no idea what to do. I have called a random string of numbers with the %random% function, but I have no idea how to permanently replace certain characters in my variable:

@echo off
set subkey1=%random%%random%%random%%random%%random%%random%
set subkey2=%random%%random%%random%%random%%random%%random%
set subkey3=%random%%random%%random%%random%%random%%random%


ECHO %subkey1:0=a%
ECHO %subkey1:1=b%
ECHO %subkey1:2=c%
ECHO %subkey1:3=d%
ECHO %subkey1:4=e%
ECHO %subkey1:5=f%
ECHO %subkey1:6=g%
ECHO %subkey1:7=h%
ECHO %subkey1:8=i%
ECHO %subkey1:9=j%

ECHO %subkey2:0=k%
ECHO %subkey2:1=l%
ECHO %subkey2:2=m%
ECHO %subkey2:3=n%
ECHO %subkey2:4=o%
ECHO %subkey2:5=p%
ECHO %subkey2:6=q%
ECHO %subkey2:7=r%
ECHO %subkey2:8=s%
ECHO %subkey2:9=t%

ECHO %subkey3:0=u%
ECHO %subkey3:1=v%
ECHO %subkey3:2=w%
ECHO %subkey3:3=x%
ECHO %subkey3:4=y%
ECHO %subkey3:5=z%
REM after going through all the letters, we just pick random ones
ECHO %subkey3:6=a%
ECHO %subkey3:7=g%
ECHO %subkey3:8=k%
ECHO %subkey3:9=o%

set key=%subkey1%%subkey2%%subkey3%
echo String: %key%
pause

So as you can see, I am able to ECHO different keys, but I want to save the new one to the variable (EX in subkey 1, I wanna replace all the 0s by a's, then SAVE that so if I look at my variable afterwards, I can see the new one, and be able to call that in different functions.

回答1:

To assign a variable a value, use the SET command:

SET subkey1=%random%%random%%random%%random%%random%%random%

SET subkey1=%subkey1:0=a%
SET subkey1=%subkey1:1=b%
SET subkey1=%subkey1:2=c%
.
.
.
ECHO %subkey1%

And, of course, beware that %random% should never, ever be used as a source for cryptographic purposes.



回答2:

same effect with much less code:

@echo off
setlocal enabledelayedexpansion
set "string=abcdefghijklmnopqrstuvwxyz"
set "result="
for /L %%i in (1,1,30) do call :add
echo %result%
goto :eof

:add
set /a x=%random% %% 26 
set result=%result%!string:~%x%,1!
goto :eof


回答3:

@echo off
setlocal EnableDelayedExpansion
set charSets=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*
set count=0

set /a countRaw=4+(%random%)%%20

for /L %%c in (1,1,%countRaw%) do (call :MAKERANDOMSTRING)
goto ENDRANDOMSTRING;

:MAKERANDOMSTRING
set buffer=% %
set count=0
set /a lowValue=30+(%random%)%%40
set /a length=10+!lowValue!

:Loop
set /a count+=1
set /a rand=%Random%%%69
set buffer=!buffer!!charSets:~%rand%,1!
if !count! leq !length! goto Loop

echo "%buffer%"
:ENDRANDOMSTRING