Shell case study on the three-generation random number seven ways

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


first, the question


it is sometimes necessary to use random numbers under the shell to summarize the method of generating random numbers. The computer produces only "pseudo-random numbers" and does not produce absolute random numbers (which is an ideal random number). pseudo-random numbers are not necessarily unique when they are reproduced in large numbers, but a good pseudo-random generation algorithm can produce a very long, non-repeating sequence .


second, random number1. Seven ways to generate random numbers


(1) Through internal system variables ($RANDOM)



Echo $RANDOM



Generates an integer random number between 0-32767, and if more than 5 bits can be added to a fixed 10-bit integer, then the remainder is obtained.



generate a random number of 400000~500000 :




#! / 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 functions that use awk



awk ' Begin{srand ();p rint rand () *1000000} ' #可以加上if判断, 779644



(3) OpenSSL rand generates random numbers



OpenSSL Rand is used to produce random characters of a specified length of bytes. -base64 or-hex base64 encode random strings or display them in hex format.



OpenSSL Rand-base64 8 | md5sum | Cut-c1-8 #八位字母和数字的组合, 3a61800e



OpenSSL Rand-base64 8 | Cksum | Cut-c1-8 # Eight digits ,10784736



(4) get random numbers by Time (date)



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:




    #!/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) via unique data within the system



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



The /dev/Urandom is a non-blocking random number generator that does not generate blocking, faster, and less secure random number generators when read.



Cat/dev/urandom | Head-n 10 | md5sum | Head-c #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 # generates a random string of numbers plus letters , QL2Q9CXS



which Strings-n Sets the number of characters in a string, Head-n Sets the number of rows to output.



head-200/dev/urandom| cksum |cut-d" " -f1   #urandom的数据很多使用cat会比较慢,在此使用head读200行,cksum将读取文件内容生成唯一的表示整型数据,cut以” “分割然后得到分割的第一个字段数据



(6) Read the Linux UUID code



The UUID code is the universal unique identifier (universally unique Identifier, UUID), and the UUID format is: Contains 32 16 binary number, with "-" connection number divided into five segments, in the form of a 8-4-4-4-12 32 characters . The UUID code of Linux is also provided by the kernel, in/proc/sys/kernel/random/uuid this file.cat/proc/sys/kernel/random/uuideach time you get the data, it will be different.



cat/proc/sys/kernel/random/uuid| Cksum | Cut-f1-d "" #获取不同的随机整数, 1675034933



cat/proc/sys/kernel/random/uuid| md5sum | CUT-C1-8 # number plus the random number of letters, D69A7EBF



generate 100~500 random numbers using the Linux UUID :




   #!/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 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))}



Used to generate a string of numbers and letters of a specific length, and 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 number in the Internet applications such as computer simulation simulation, data encryption, network games, etc., in certain forums or games, the system will produce a random number and letters of the picture, the user must enter correctly, this is a good way to prevent malicious attacks, because it is difficult to crack the image format characters. The key technique is to generate random numbers, and then use tools such as ASP. To encapsulate these strings in a picture format as a validation picture.





(2) Online games often use random numbers to complete a number of functions, such as throwing dice, playing poker and so on. The following is a continuous roll of 1000 dice , and then count the number of 1~6 points:




#!/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 is basically floating around the average (i.e., the variance is small).



(3) Batch creation of 10 system accounts, password random



First look at the script that specifies the user's password:





#! / bin / bash
#Create 10 system accounts in batches and set passwords, 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
10 user username and password are the same from linux-01 to linux-10, and then look at the user password randomly generated script:



#! / 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 
As you can see, the flexibility and confidentiality of randomly generated passwords allows administrators to open the User.log file and record the information of the 10 users who have just created it.




Iii. Summary


(1) The shell generates pseudo-random number function $random, can easily produce the distributed more average pseudo-random number, can meet the needs of most applications.



(2) There are many ways to generate random numbers and they can be extended to expand the way you choose the most recent.



Shell case study on the three-generation random number seven ways


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.