曲径通幽论坛

标题: 获取随机数 [打印本页]

作者: beyes    时间: 2011-4-29 10:52
标题: 获取随机数
常用且简单的方法就是使用 $RANDOM 环境变量:
[root@centos shell]# echo $RANDOM
25758
[root@centos shell]# echo $RANDOM
32276
[root@centos shell]# echo $RANDOM
31909
[root@centos shell]# echo $RANDOM
9871
但该变量的范围是 0-32767 。

如果希望再大一点,可使用 date 命令产生的纳秒:

[root@centos shell]# date +%N
949499000
[root@centos shell]# date +%N
453678000
[root@centos shell]# date +%N
647890000
[root@centos shell]# date +%N
685699000

还可以通过读取 /dev/urandom 设备来获取:

# head -200 /dev/urandom |cksum
3971052498 47438
# head -200 /dev/urandom |cksum
2697064411 52938
这里不能用 cat 来读取 /dev/urandom ,这样数据量太大,而且还不会停下来。
上面的输出有两个两列,可以使用 cut 命令将第 2 列的数据剪掉:

# head -200 /dev/urandom |cksum |cut -f1 -d " "
313148969

还可以通过 uuid 码来获取随机数,uuid 码可以通过读取 /proc/sys/kernel/random/uuid 文件获得:
# cat /proc/sys/kernel/random/uuid
3b3c95bd-b8c0-406d-bfd9-a7806d6ab036

仍然可以用 cksum 获得随机数:
# cat /proc/sys/kernel/random/uuid |cksum |cut -f1 -d " "
1028200979





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2