shell實例淺談之一產生隨機數七種方法


一、問題

     Shell下有時需要使用隨機數,在此總結產生隨機數的方法。計算機產生的的只是“偽隨機數”,不會產生絕對的隨機數(是一種理想隨機數)。偽隨機數在大量重現時也並不一定保持唯一,但一個好的偽隨機產生算法將可以產生一個非常長的不重復的序列。

二、生成隨機數的七種方法

(1)通過內部系統變量($RANDOM)

[gin@Gin ~]$ echo $RANDOM
6936
[gin@Gin ~]$ echo $RANDOM
28058
[gin@Gin ~]$ echo $RANDOM
21427

生成0-32767之間的整數隨機數,若超過5位可以加個固定10位整數,然后進行求余。

生成400000~500000的隨機數:

#!/bin/bash    
    
function rand(){    
    min=$1    
    max=$(($2-$min+1))    
    num=$(($RANDOM+1000000000)) #增加一個10位的數再求余    
    echo $(($num%$max+$min))    
}    
    
rnd=$(rand 400000 500000)    
echo $rnd    
    
exit 0 

(2)使用awk的隨機函數

[root@Gin scripts]# awk 'BEGIN{srand();print rand()*1000000}'   ##可以加上if判斷,779644
918520
[root@Gin scripts]# awk 'BEGIN{srand();print rand()*1000000}'
379242

(3)openssl rand產生隨機數

openssl rand 用於產生指定長度個bytes的隨機字符。-base64或-hex對隨機字符串進行base64編碼或用hex格式顯示。

[root@Gin scripts]# openssl rand -base64 8
wBroG6n//3c=
[root@Gin scripts]# openssl rand -base64 8|md5sum
99b965644182c16b04472ed5f922c5c2  -
[root@Gin scripts]# openssl rand -base64 8|md5sum|cut -c 1-8   #八位字母和數字的組合
567f5d54
[root@Gin scripts]# openssl rand -base64 8|cksum|cut -c 1-8  #八位數字
70083590

(4)通過時間獲得隨機數(date)

[root@Gin scripts]# date +%s%N  #生成19位數字
1486113479463684835
[root@Gin scripts]# date +%s%N|cut -c 6-13  #取八位數字
13578053
[root@Gin scripts]# date +%s%N|md5sum|head -c 8  #八位字母和數字的組合
11f60e3a

生成1~50的隨機數:

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)通過系統內唯一數據生成隨機數(/dev/random及/dev/urandom)

/dev/random存儲系統當前運行的環境的實時數據,可以看作系統某時候的唯一值數據,提供優質隨機數。

/dev/urandom是非阻塞的隨機數產生器,讀取時不會產生阻塞,速度更快、安全性較差的隨機數發生器。

[root@Gin scripts]# cat /dev/urandom|head -n 10|md5sum|head -c 10
dc32c5047f

[root@Gin scripts]# cat /dev/urandom|strings -n 8|head -n 1  #生成全字符的隨機字符串
}pFYi%%D~
[root@Gin scripts]# cat /dev/urandom|strings -n 8|head -n 1
        M(,FG+=
[root@Gin scripts]# cat /dev/urandom|strings -n 8|head -n 1
|NR{$LY%

[root@Gin scripts]# cat /dev/urandom|sed -e 's#[^a-zA-Z0-9]##g'|strings -n 8|head -n 1
aPdKtMod
#生成數字加字母的隨機字符串,其中 strings -n設置字符串的字符數,head -n設置輸出的行數。

[root@Gin scripts]# head -200 /dev/urandom|cksum|cut -d " " -f1
1182233652
#urandom的數據很多使用cat會比較慢,在此使用head讀200行,cksum將讀取文件內容生成唯一的表示整型數據,cut以” “分割然后得到分割的第一個字段數據

(6)讀取Linux的uuid碼

UUID碼全稱是通用唯一識別碼 (Universally Unique Identifier, UUID),UUID格式是:包含32個16進制數字,以“-”連接號分為五段,形式為8-4-4-4-12的32個字符。linux的uuid碼也是有內核提供的,在/proc/sys/kernel/random/uuid這個文件內。cat/proc/sys/kernel/random/uuid每次獲取到的數據都會不同。

[root@Gin scripts]# cat /proc/sys/kernel/random/uuid |cksum|cut -f1 -d " "  #獲取不同的隨機整數
3838247832
[root@Gin scripts]# cat /proc/sys/kernel/random/uuid |md5sum|cut -c 1-8  #數字加字母的隨機數
6092539b

使用linux uuid 生成100~500隨機數:

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)從元素池中隨機抽取取

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))]}

用於生成一段特定長度的有數字和字母組成的字符串,字符串中元素來自自定義的池子。

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

執行該腳本得到以下結果:

[root@Gin scripts]# sh seqrand.sh 
The random string is:
aOvZcYOZ
[root@Gin scripts]# sh seqrand.sh 
The random string is:
Eylv8JHr
[root@Gin scripts]# sh seqrand.sh 
The random string is:
1sJd2GT8

三、隨機數應用

(1)隨機數在互聯網中應用廣泛如計算機仿真模擬、數據加密、網絡游戲等,在登錄某些論壇或游戲時,系統會產生一個由隨機數字和字母組成的圖片,用戶必須正確輸入,這是防止惡意攻擊的很好的方法,因比較難破解圖片格式的字符。其關鍵技術就是產生隨機數,再使用ASP.NET等工具將這些字符串封裝成圖片格式以作為驗證圖片。

(2)網絡游戲中也常利用隨機數完成一些功能,比如擲骰子、發撲克牌等。以下是連續擲1000次骰子,然后統計出1~6點的次數:

#!/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"  

RANDOM產生的隨機數基本在平均值左右浮動(即方差較小)。

(3)批量創建10個系統帳號,密碼隨機

先看看指定用戶密碼的腳本:

#!/bin/bash  
#批量創建10個系統帳號並設置密碼,帳號和密碼相同  
for name in `seq -w 10`  
do  
    #非交互式的輸入密碼  
    useradd linux$name && echo "linux$name" | passwd --stdin linux$name  
done 

10個用戶用戶名和密碼相同都從linux-01到linux-10,再看看用戶密碼隨機生成的腳本:

#!/bin/bash  
#批量創建10個系統帳號並設置密碼  
rm -f user.log  
for name in `seq -w 10`  
do  
    #非交互式的輸入隨機密碼  
    password=`echo $RANDOM | md5sum | cut -c1-8`  
    #可以使用password=`echo "date $RANDOM" | md5sum | cut -c3-11`  
    #也可以使用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   #保存用戶名密碼以查閱  
done

對比可以看出,隨機生成密碼的靈活性和保密性,管理員可以打開user.log文件,記錄剛創建的十個用戶的信息。

四、總結

(1)Shell產生偽隨機數的函數$RANDOM,能方便地產生分布較平均的偽隨機數,能滿足大部分應用的需求。

(2)產生隨機數的方法還有很多並且可以擴展,擴展思路才能選擇最近的方式。

 

本文章轉載自:http://blog.csdn.net/taiyang1987912/article/details/39997303


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM