Shell instances seven methods of generating random numbers

Source: Internet
Author: User
Tags base64 base64 encode stdin uuid

I. Problems
     Sometimes it is necessary to use a random number under the shell, and here is a summary of the method of generating a random number. What a computer generates is just a "pseudo-random number", it does not produce an absolute random number (it is an ideal random number). Pseudo-random numbers do not necessarily remain unique when reproduced in large numbers, but a good pseudo-random generation algorithm will produce a very long, non-repeating sequence.

Second, random numbers, seven methods to generate random numbers
(1) Via the internal system variable ($ RANDOM)

echo $ RANDOM

Generate an integer random number between 0 and 32767. If it exceeds 5 digits, you can add a fixed 10 digit integer and then perform the remainder.

Generate random numbers from 400,000 to 500,000:

 

[cpp] view plaincopy
#! / bin / bash
    
function rand () {
    min = $ 1
    max = $ (($ 2- $ min + 1))
    num = $ (($ RANDOM + 1000000000)) #Increase 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}’ #You can add if judgment, 779644

(3) openssl rand generates random numbers

openssl rand is used to generate random characters of the specified length bytes. -base64 or -hex Base64 encode a random string or display it in hex format.

openssl rand -base64 8 | md5sum | cut -c1-8 #A combination of eight letters and numbers, 3a61800e

openssl rand -base64 8 | cksum | cut -c1-8 # eight-digit number, 10784736

(4) Obtain a random number (date) by time

date +% s% N #Generate 19 digits, 1287764807051101270

date +% s% N | cut -c6-13 #take eight digits, 21793709

date +% s% N | md5sum | head -c 8 #A combination of eight letters and numbers, 87022fda

Generate random numbers from 1 to 50:

 

[cpp] view plaincopy
#! / bin / bash
    
function rand () {
    min = $ 1
    max = $ (($ 2- $ min + 1))
    num = $ (date +% s% N)
    echo $ (($ num% $ max + $ min))
}
    
rnd = $ (rand 1 50)
echo $ rnd
    
exit 0
(5) Generate random numbers from the unique data in the system (/ dev / random and / dev / urandom)

/ dev / random stores real-time data of the environment in which the system is currently running, which can be considered as the unique value data of the system at some time, providing high-quality random numbers.

/ dev / urandom is a non-blocking random number generator. It does not generate blocking 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 a random string of all characters, 08? WU $ ZU

cat / dev / urandom | sed -e ‘s / [^ a-zA-Z0-9] // g’ | strings -n 8 | head -n 1 #Generate 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 lines to output.

head-200 / dev / urandom | cksum | cut-d "" -f1 # urandom's data is much slower using cat. Here, read 200 lines using head, cksum will read the file content to generate unique integer data, cut with "" and then get the first field data

(6) Read the uuid code of Linux

       The full name of the UUID code is a Universally Unique Identifier (UUID). The UUID format is: Contains 32 hexadecimal digits. It is divided into five segments by a "-" connection number. The format is 8-4-4-4-12. 32 characters. Linux uuid code is also provided by the kernel, in the file / proc / sys / kernel / random / uuid. cat / proc / sys / kernel / random / uuid will get 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

Use linux uuid to generate 100 ~ 500 random numbers:

 

[cpp] view plaincopy
#! / bin / bash
    
function rand () {
    min = $ 1
    max = $ (($ 2- $ min + 1))
    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 drawn 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)

num = $ {# pool [*]}

result = $ {pool [$ ((RANDOM% num))]}

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

 

[cpp] view plaincopy
#! / bin / bash
length = 8
i = 1
  
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)
  
num_seq = $ {# seq [@]}
  
while ["$ i" -le "$ length"]
do
 seqrand [$ i] = $ {seq [$ ((RANDOM% num_seq))]}
 let "i = i + 1"
done
  
echo "The random string is:"
for j in $ {seqrand [@]}
do
 echo -n $ j
done
echo
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 certain forums or games, the system will generate a picture composed of random numbers and letters. Users must enter correctly Is a good way to prevent malicious attacks, because it is more difficult to crack the characters in the picture format. The key technology is to generate random numbers, and then use tools such as ASP.NET to package these strings into image formats for verification images.

(2) In online games, random numbers are often used to complete some functions, such as rolling dice and playing cards. The following is a roll of 1000 dice in a row, and then count the number of 1 to 6 points:

 

[cpp] view plaincopy
#! / bin / bash
  
#RANDOM = $$
  
PIPS = 6
MAX = 1000
throw = 1
  
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
  
count ()
{
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" ;;
esac
}
  
while ["$ throw" -le "$ MAX"]
do
  let "dice = RANDOM% $ PIPS"
  count $ dice
  let "throw = throw + 1"
done
  
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 (ie, the variance is small).

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

First look at the script that specifies the user password:

[cpp] view plaincopy
#! / bin / bash
#Create 10 system accounts in batches and set passwords, and the accounts and passwords are the same
for name in `seq -w 10`
do
    # Non-interactive input password
    useradd linux $ name && echo "linux $ name" | passwd --stdin linux $ name
done
The ten user names and passwords are all the same from linux-01 to linux-10, and then look at the script that the user password randomly generates:

 

[cpp] view plaincopy
#! / bin / bash
#Create 10 system accounts in batches and set passwords
rm -f user.log
for name in `seq -w 10`
do
    # Non-interactive input of random password
    password = `echo $ RANDOM | md5sum | cut -c1-8`
    # 可用 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 username and password for review
done
The comparison shows that the flexibility and confidentiality of randomly generated passwords allows the administrator to open the user.log file and record the information of the ten users just created.

Summary
(1) The shell generates a pseudo-random number function $ RANDOM, which can easily generate a more evenly distributed pseudo-random number, which can meet the needs of most applications.

(2) There are still many methods for generating random numbers and they can be expanded. Only by expanding ideas can we choose the nearest method.

(Transfer) seven methods of shell examples to generate random numbers

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.