Linux Shell生成随机数和随机字符串的5种方法

使用系统的 $RANDOM 变量

(CentOS、Ubuntu、MacOS 都支持,但只有5位数随机)

echo $RANDOM
24308

使用date +%s%N

(CentOS、Ubuntu支持,MacOS不支持纳秒 +%N)

date +%s%N
1557366636971317933

使用 /dev/random 和 /dev/urandom 随机文件

(CentOS、Ubuntu、MacOS 都支持)

head -20 /dev/urandom | cksum | cut -f1 -d " "
1053195602

使用 linux uuid

(CentOS、Ubuntu支持,MacOS不支持)

cat /proc/sys/kernel/random/uuid
bf05d41c-d69e-4247-8a79-baf3ab3f98ed

使用 openssl rand

(CentOS、Ubuntu支持、MacOS 都支持,需安装 openssl,推荐)

openssl rand -base64 128 
Smt+jcaMSQ64Y4La8U6OUFl/TZWm+cKGtDqg+MRbKY6Zwp5iOzg3xoVZv+6NQv/W 
UL+sqAHBhbTD1ZPgsyeloxTVLRV/SjU2O/mJAZoFLLZXtDhldl5lfgz3s3s28R+u 
24TUNXnxGLGqQQxaudcF8Lhgq3LjDLQWzrgrTOIv1e0=

openssl rand -base64 128 | md5sum | cut -c1-32 
2cbb48ea9bac4b08c2a9b4518e1faf79

openssl rand -hex 16 
339a905406bb4ef3631dfa1ad67d8d6a

openssl rand -hex 8 | cksum 
307618125 17

openssl rand -hex 8 | cksum | cut -c1-8 
41657201

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

*

code