Bash script to read from /dev/urandom

人盡茶涼 提交于 2019-12-24 08:38:53

问题


I want to make bash script that sends to stdout a file image containing only ASCII writable characters. My script should receive and accept only one argument containing the number of octets that should be read from /dev/urandom.

So, I need to read a given number of octets from /dev/urandom to create a file image to send to stdout.

I have this:

!/usr/bin/env bash

X=1

if [ $X -eq 0 ]; then
    echo "Error: An argument is needed"
else
    strings /dev/urandom    
    echo the result
fi

I'm checking if there's any argument and, if there is, read the /dev/urandom. Of course this is just a sketch.

I was told there is a command called strings that reads and extracts sequences of characters from any file, but I've checked on the internet and I can't find much info about it.

So my question is: How do I read the number of octets given in the arguments from /dev/random so that I can put them in stdout (I know how to put on stdout :) )


回答1:


strings is not what you want. If you just want random characters restricted to a particular set, filter out what you do not want. To get $num alphanumeric chars from /dev/urandom, you can do:

tr -dc A-Za-z0-9 < /dev/urandom | dd bs=$num count=1 2> /dev/null

or

tr -dc '[:alnum:]' < /dev/urandom ...

Note that this is not strictly portable. Although the standard for tr states that it should work on any input file, my version is throwing the error 'Illegal byte sequence'. Another option is:

perl -pe 's/[^a-zA-Z0-9]//g' /dev/urandom | dd bs=$num count=1 2> /dev/null


来源:https://stackoverflow.com/questions/19223871/bash-script-to-read-from-dev-urandom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!