7 methods for generating random numbers in shell instances

Source: Internet
Author: User

7 methods for generating random numbers in shell instances
I. Problems

A random number is sometimes used in Shell, and the method for generating the random number is summarized here. Computers generate only pseudo-random numbers and do not generate absolute random numbers (an ideal random number ). Pseudo-Random numbers are not necessarily unique in a large number of duplicates, but a good pseudo-random generation algorithm can generate a very long non-repeating sequence.

Ii. Random Number 1. Seven methods for generating random numbers

(1) using internal system variables ($ RANDOM)

Echo $ RANDOM

Generate an integer random number between 0 and. If the number of digits exceeds 5, add a fixed 10-digit integer and perform the remainder operation.

Generate 400000 ~ A Random Number of 500000:


/bin/bash!
function rand(){
Min=$1
max=$(($2-$min+1))
Num = $(($random + 1000000000)) //add a 10 bit number and then calculate the remaind
echo $(($num%$max+$min))
}
rnd=$(rand 400000 500000)
Echo $rnd
Exit 0


(2) Use Random Functions of awk

Awk 'in in {srand (); print rand () * 1000000} '# if judgment can be added, 779644

(3) openssl rand generates random numbers.

Openssl rand is used to generate random characters with a specified length of bytes. -Base64 or-hex: encode random strings in base64 or display them in hex format.

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

Openssl rand-base64 8 | cksum | cut-c1-8 # octal, 10784736

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

Date + % s % N # generate 19 digits,1287764807051101270

Date + % s % N | cut-c6-13 # octal characters, 21793709

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

Generate 1 ~ Random Number of 50:


  #!/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 (/dev/random and/dev/urandom) based on the unique data in the system)

/Dev/random stores the real-time data of the current running environment of the system, which can be regarded as the unique value data at a certain time in the system and provides high-quality random numbers.

/Dev/urandom is a non-blocking random number generator. It does not block the random number generator during reading, which is faster and less secure.

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 random strings with numbers and letters, Ql2q9CXS

Here, 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 dataMany cat operations are slow. Here, we use head to read 200 rows,Cksum will read the file content to generate a unique integer data,Cut is separated by "" and the first field data is obtained.

(6) read the uuid code of linux

UUID is a universal Unique Identifier (UUID). The UUID format is: contains 32 hexadecimal numbers. The "-" connection number is divided into five segments, the format is 8-4-4-4-12 32 characters. Linux uuid code is also provided by the kernel in the/proc/sys/kernel/random/uuid file.cat/proc/sys/kernel/random/uuidThe data obtained each time is different.

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 # random number of digits plus letters, d69a7ebf

Use linux uuid to generate 100 ~ 500 Random Number:


  #!/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) random extraction from 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 consisting of numbers and letters with a specific length. The elements in the string come from a custom pool.


#!/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, and online games. When logging on to some forums or games, the system generates an image composed of random numbers and letters. Users must enter the image correctly. This is a good way to prevent malicious attacks, because it is difficult to crack the characters in the image format. The key technology is to generate random numbers, and then use tools such as ASP. NET to encapsulate these strings into image formats for image verification. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + pgltzybzcm9 "http://www.2cto.com/uploadfile/Collfiles/20141012/20141012091827225.png" alt = "\" width = "171" height = "113">

(2) online games also often use random numbers to complete some functions, such as rolling dice and playing cards. The following figure shows how to throw a dice for 1000 consecutive times ~ Number of times:


#!/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 floats around the average value (that is, the variance is small ).

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

First look at the script for the specified user password:


/bin/bash!
#Create 10 system accounts in batch and set passwords. The accounts and passwords are the same
for name in `seq -w 10`
Do
#Non interactive input password
useradd linux$name &amp;&amp; echo "linux$name" | passwd --stdin linux$name
Done
The 10 user usernames and passwords are the same from the linux-01 to the linux-10, and then look at the user password randomly generated script:


/bin/bash!
#Batch create 10 system accounts and set password
rm -f user.log
for name in `seq -w 10`
Do
#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 &amp;&amp; echo password | passwd --stdin linux$name
Echo - e "user = Linux $name \ t passwd = $password" >
Done 
The comparison shows the flexibility and confidentiality of randomly generated passwords. The administrator can open the user. log File and record the information of the 10 users just created.


Iii. Summary

(1) The Shell function $ RANDOM that generates pseudo-RANDOM numbers can easily generate pseudo-RANDOM numbers with relatively average distribution and meet the needs of most applications.

(2) there are still many ways to generate random numbers and they can be extended. The idea of extension is to select the nearest method.


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.