Generate Random Passwords On The Terminal
This is a sysadmin lifehack I came to appreciate. Wether you are configuring servers for work or for your own projects, you might end up in the following situation. You are in an ssh session and someone sits down next to you and starts talking. Now, you have four eyes on your screen while configuring a service. You need to write a password to a file, but you want to do so without revealing it to the person next to you.
My solution for this is as follows: prepare a command that generates a random password and bind it to a shell alias, such as “genpw”. Then, you can do “genpw > passfile.txt” to populate the passfile.
Example Command
RANDOM=10#$(date +%N) && pwlength=$((41 + $RANDOM % 35)) && cat /dev/urandom | tr -dc 'a-zA-Z0-9.]}{[#,/;:><?=+-' | fold -w $pwlength | head -n 1
This will generate a long, random password. The length is decided with the help of the $RANDOM variable, using the current nanoseconds as seed. /dev/urandom is used to generate the password characters. Any characters that don’t match the character set specified in the “tr -dc …” command will not make it into the output. This also means that you can expand or shorten the set of allowed characters by editing the command.
If you call the command without using the > operator to put the output into a file, the password will be printed to your terminal. This allows you to do some test runs before >‘ing a password into the target file. The command should generate a different password each time.
As far as I understand random number generation in Linux, results should be sufficiently random. Feel free to correct me if I am wrong.