如何通过命令行获取32位十六进制数字的随机字符串? [英] How to get a random string of 32 hexadecimal digits through command line?

查看:415
本文介绍了如何通过命令行获取32位十六进制数字的随机字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想组合一个命令,该命令将打印出一个包含32个十六进制数字的字符串.我有一个可以正常工作的Python脚本:

I'd like to put together a command that will print out a string of 32 hexadecimal digits. I've got a Python script that works:

python -c 'import random ; print "".join(map(lambda t: format(t, "02X"), [random.randrange(256) for x in range(16)]))'

这将生成如下输出:

6EF6B30F9E557F948C402C89002C7C8A 

我需要什么.

在Mac上,我什至可以执行以下操作:

On a Mac, I can even do this:

uuidgen | tr -d '-'

但是,我无法使用更复杂的脚本语言ruby和python,而且我也不会使用Mac(因此没有uuidgen).我需要使用诸如sed,awk,/dev/random之类的更流行的工具,因为我的平台有限.有办法吗?

However, I don't have access to the more sophisticated scripting languages ruby and python, and I won't be on a Mac (so no uuidgen). I need to stick with more bash'ish tools like sed, awk, /dev/random because I'm on a limited platform. Is there a way to do this?

推荐答案

如果您拥有hexdump,则:

hexdump -n 16 -e '4/4 "%08X" 1 "\n"' /dev/random

应该做的工作.

说明:

  • -n 16消耗16个字节的输入(32个十六进制数字= 16个字节).
  • 4/4 "%08X"进行四次迭代,每次迭代消耗4个字节,并在需要时将相应的32位值打印为8个十六进制数字,并带有前导零.
  • 1 "\n"以单个换行符结尾.
  • -n 16 to consume 16 bytes of input (32 hex digits = 16 bytes).
  • 4/4 "%08X" to iterate four times, consume 4 bytes per iteration and print the corresponding 32 bits value as 8 hex digits, with leading zeros, if needed.
  • 1 "\n" to end with a single newline.

注意:此解决方案使用/dev/random,但也可以使用/dev/urandom.两者之间的选择是一个复杂的问题,超出了此答案的范围.如果您不确定,可以看看另一个问题.

Note: this solution uses /dev/random but it could as well use /dev/urandom. The choice between the two is a complex question and out of the scope of this answer. If you are not sure, have a look maybe at this other question.

这篇关于如何通过命令行获取32位十六进制数字的随机字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆