8

生成随机数的若干种方法 - 静言善思

 2 years ago
source link: https://www.cnblogs.com/xiong97/p/16640850.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

  创建账户时我们需要配置初始随机密码,使用手机号注册时需要随机验证码,抽奖活动需要随机点名,俄罗斯方块游戏需要随机出形状。这些案例都在说明一个问题,随机数据很重要!而在 Shell 脚本中如果需要生成随机数据有哪些方式呢?下面我们依次看看都有哪些方式。

方法一:使用字符串截取提取随机密码

定义字符串取值范围,利用随机截取一位,通过循环迭代,拼凑取出适合长度的字符串

#  自定义变量: 例如 10 个数字+52 个字符(26位英文字母大小写)
key="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

randpass(){ if [ -z "$1" ];then echo "randpass 函数需要一个参数,用来指定提取的随机数个数." return 127 fi#调用$1 参数,循环提取任意个数据字符#用随机数对 62 取余数,返回的结果为[0-61] pass="" for i in `seq $1` do num=$[RANDOM%${#key}] local tmp=${key:num:1} pass=${pass}${tmp} done echo $pass}randpass 8

方法二:使用命令生成随机数据

Linux 本身有些命令是可以提供随机字符串,或者是对一些字符串进行加密,通过调用这些命令生成的字符串配合一些截取命令,可以轻松获得指定长度的随机字符串。

[root@centos7 ~]# uuidgen #生成 16 进制随机字符串d1c7c974-2e94-4f31-bdd7-0b2f697aea6b
[root@centos7 ~]# openssl rand -hex 4 #生成 16 进制随机字符串38a61465
[root@centos7 ~]# openssl rand -base64 67ZwWj1hX
[root@centos7 ]# echo 123|md5sumba1f2511fc30423bdbb183fe33f3dd0f[root@centos7 ]# a=$(echo 123|sha256sum)[root@centos7 ]## echo ${a:1:6}81210f[root@centos7 ]# echo "test$RANDOM"|md5sum|cut -c 8-15 # 截取8-15 位置的字符串433bacdc
通过时间(date)获得随机数 [root@centos7 /]# date +%s%N1661868951447501276
通过UUID生成随机数[root@centos7 /]# cat /proc/sys/kernel/random/uuid54b63594-98f3-4f41-b50f-3c152dce170e

方法三:使用设备文件生成随机数据 

在 Linux 操作系统中默认提供了两个可以生成随机数据的设备文件:/dev/random 和/dev/urandom

提取 10 位包含字母、数字和下画线的随机数据。[root@centos7 ~]# tr -cd '_a-zA-Z0-9' < /dev/random | head -c 10aw23954A9[root@centos7 ~]# tr -cd '_a-zA-Z0-9' < /dev/urandom | head -c 10LiV9uZVyJN提取 10 位包含存数字的随机数据。[root@centos7 ~]# tr -cd '0-9' < /dev/random | head -c 107565203215[root@centos7 ~]# tr -cd '0-9' < /dev/urandom | head -c 105690607214

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK