bash: generating random passwords on Mac OS X / MacOS or what Apple calls their operating system by now
Posted by jpluimers on 2018/08/14
After some fiddling, I put this function in ~/bash_profile on my MacBook:
# https://www.cyberciti.biz/tips/linux-unix-bsd-openssh-server-best-practices.html
# pass # digits as first argument; defaults to 20
generate_password() {
local l=$1
[ "$l" == "" ] && l=20
env LC_CTYPE=C LC_ALL=C tr -dc A-Za-z0-9_ < /dev/urandom | head -c ${l} | xargs
}
The fiddling was working around this error:
tr: Illegal byte sequence
The cause is that Mac OS is not Linux, where tr happily accepts any byte sequence from /dev/urandom: it requires the C locale.
Originally, I started with the below function from [WayBack] Top 20 OpenSSH Server Best Security Practices – nixCraft (thanks +Joe C Hecht) which I undid from mixed tab/spaces:
genpasswd() {
local l=$1
[ "$l" == "" ] && l=20
tr -dc A-Za-z0-9_ < /dev/urandom | head -c ${l} | xargs
}
Via: [WayBack] Joe C. Hecht – Google+ who mentions:
I might add that if you do move the SSH port, try to keep it in within the first 1024 ports for a tad bit more protection on some systems.
Background reading on Apple hating binary input:
- [WayBack] tr: Illegal byte sequence | s9y testdrive
- [WayBack] random – Why can’t tr read from /dev/urandom on OSX? – Unix & Linux Stack Exchange
- [Archive.is] generate random password (works on Mac OS X) | commandlinefu.com
Background reading on the language setting:
- [WayBack] Locale – POSIX Locale
- [WayBack] Why do Monitor Solution command lines contain LC_ALL=C?
- [WayBack] environment variables – What does “LC_ALL=C” do? – Unix & Linux Stack Exchange
- [WayBack] environment variables – What does C in LC_ALL=C mean? – Ask Ubuntu
–jeroen






ruurd said
The operating system that runs om Apple Mac computers is nowadays called macOS with a lowercase ‘m’ and uppercase ‘OS’.
jpluimers said
Right. That’s exactly the thing I meant. With so many renames, and addressing older versions too, I am not sure how to call their OS any more.