Implementation of seven methods of generating random numbers by shell


1、 Question

Random numbers sometimes need to be used in shell. The methods of generating random numbers are summarized here. What the computer produces is only “pseudo-random number”, which will not produce absolute random number (an ideal random number). Pseudorandom numbers are not necessarily unique when they are reproduced in large numbers, but a good pseudorandom generation algorithm can produce a very long non repetitive sequence.

2、 Random number

1. Seven methods of generating random numbers

(1) Through the internal system variable ($random)

echo $RANDOM

Generate an integer random number between 0-32767. If it exceeds 5 bits, add a fixed 10 bit integer, and then calculate the remainder.

Generate 400000 ~ 500000 random numbers:

function rand(){ 
 Num = $(($random + 1000000000)) # add a 10 digit number and find the remainder 
 echo $(($num%$max+$min)) 
rnd=$(rand 400000 500000) 
echo $rnd  
exit 0

(2) Random function using awk

Awk 'begin {srand(); print rand() * 1000000}' # can add if judgment

(3) OpenSSL Rand generates random numbers

OpenSSL Rand is used to generate random characters with a specified length of bytes- Base64 or – hex encodes random strings or displays them in hex format.

OpenSSL Rand - Base64 8 | md5sum | cut - c1-8 # combination of eight letters and numbers, 3a61800e
OpenSSL Rand - Base64 8 | cksum | cut - c1-8 # eight digit, 10784736

(4) Random number obtained by time (date)

Date +% s% n # generates 19 digits, 1287764807051101270
Date +% s% n | cut - c6-13 # takes eight digits, 21793709
Date +% s% n | md5sum | head - C 8 # eight letter and digit combination, 87022fda

Generate random numbers from 1 to 50:

function rand(){ 
 num=$(date +%s%N) 
 echo $(($num%$max+$min)) 
rnd=$(rand 1 50) 
echo $rnd  
exit 0 

(5) Generate random numbers (/ dev / random and / dev / urandom) from unique data in the system

/The real-time data of the current running environment of dev / random storage system can be regarded as the unique value data of the system at a certain time, providing high-quality random numbers.

/Dev / urandom is a non blocking random number generator. It will not block when reading. It is a faster and less secure random number generator.

cat /dev/urandom | head -n 10 | md5sum | head -c 10  #32f1e953ac
Cat / dev / urandom | strings - N 8 | head - N 1 # generate random strings of full characters, 08? WU$ZU
Cat / dev / urandom | sed - E's / [^ a-za-z0-9] // g '| strings - N 8 | head - N 1 # generates a random string of numbers and letters, ql2q9cxs, where strings - N sets the number of characters in the string and head - N sets the number of output lines.
Head-200 / dev / urandom | cksum | cut-d "" - F1 #urandom has a lot of data. It will be slow to use cat. Here, use head to read 200 lines. Cksum will read the file content and generate unique integer data. Cut is divided by "" and then get the first field data

(6) Read the UUID code of Linux

The full name of UUID code is universal unique identifier (UUID). The format of UUID is: 32 hexadecimal digits, divided into five segments with “-” connection number, and 32 characters in the form of 8-4-4-4-12. The UUID code of Linux is also provided by the kernel in the file / proc / sys / kernel / random / UUID. Cat / proc / sys / kernel / random / UUID gets different data each time.

Cat / proc / sys / kernel / random / UUID | cksum | cut - F1 - D "" # get different random integers, 1675034933
 Cat / proc / sys / kernel / random / UUID | md5sum | cut - c1-8 # number plus letter random number, d69a7ebf

Generate 100 ~ 500 random numbers using Linux UUID:

function rand(){ 
 num=$(cat /proc/sys/kernel/random/uuid | cksum | awk -F ' ' '{print $1}') 
 echo $(($num%$max+$min)) 
rnd=$(rand 100 500) 
echo $rnd  
exit 0

(7) Randomly extract from the element pool

pool=(a b c d e f g h i j k l m n o p q r s t 1 2 3 4 5 6 7 8 9 10)

It is used to generate a string of numbers and letters of a specific length. The elements in the string are from a custom pool.

seq=(0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) 
while [ "$i" -le "$length" ] 
 let "i=i+1" 
echo "The random string is:" 
for j in ${seqrand[@]} 
 echo -n $j 

2. Random number application

(1) Random numbers are widely used in the Internet, such as computer simulation, data encryption, online games, etc. when logging in to some forums or games, the system will generate a picture composed of random numbers and letters, which users must input correctly. This is a good method to prevent malicious attacks, because it is difficult to crack the characters in the picture format. The key technology is to generate random numbers, and then use ASP. Net and other tools to encapsulate these strings into picture format as verification pictures.

(2) In online games, random numbers are often used to complete some functions, such as dice, playing cards and so on. The following is the number of 1-6 points after rolling 1000 dice continuously:

case "$1" in 
 0) let "one=one+1";; 
 1) let "two=two+1";; 
 2) let "three=three+1";; 
 3) let "four=four+1";; 
 4) let "five=five+1";; 
 5) let "six=six+1";; 
while [ "$throw" -le "$MAX" ] 
 let "dice=RANDOM % $PIPS" 
 count $dice 
 let "throw=throw+1" 
echo "The statistics results are as follows:" 
echo "one=$one" 
echo "two=$two" 
echo "three=$three" 
echo "four=$four" 
echo "five=$five" 
echo "six=$six" 

The random number generated by random basically fluctuates around the average value (i.e. the variance is small).

(3) Create 10 system accounts in batch with random passwords

First look at the script for specifying the user password:

#Create 10 system accounts in batch and set the password. The account and password are the same 
for name in `seq -w 10` 
 #Non interactive input password 
 useradd linux$name && echo "linux$name" | passwd --stdin linux$name 

The user names and passwords of 10 users are the same, from linux-01 to linux-10. Let’s look at the script randomly generated by the user password:

#Batch create 10 system accounts and set passwords 
rm -f user.log 
for name in `seq -w 10` 
 #Non interactive input random password 
 password=`echo $RANDOM | md5sum | cut -c1-8` 
 #You can use password = ` echo "date $random" | md5sum | cut - c3-11` 
 #You can also use password = ` penssl Rand - Base64 8 | md5sum | cut - c1-8` 
 useradd linux$name && echo password | passwd --stdin linux$name 
 Echo - e "user = Linux $name \ t passwd = $password" > > user.log # save the user name and password for reference 

The comparison shows that the randomly generated password is flexible and confidential. The administrator can open the user.log file to record the information of the ten users just created.

3、 Summary

(1) Shell’s function $random, which generates pseudo-random numbers, can easily generate pseudo-random numbers with average distribution, and can meet the needs of most applications.

(2) There are many methods to generate random numbers, and they can be expanded. Only by expanding the idea can we choose the nearest way.

This is the end of this article on the implementation of seven methods of shell generating random numbers. For more information about shell random numbers, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!