diff options
author | Aaron LI <aly@aaronly.me> | 2019-04-25 08:49:30 +0800 |
---|---|---|
committer | Aaron LI <aly@aaronly.me> | 2019-04-25 08:49:30 +0800 |
commit | 5926594690f03cf282b856cc53facbea8a42d88c (patch) | |
tree | 284ee1e7894de068c8fb7e3a11e2226d799ecbc7 | |
parent | 0718f904a15d17ee87e822fd6c6b08a3a7774317 (diff) | |
download | atoolbox-5926594690f03cf282b856cc53facbea8a42d88c.tar.bz2 |
Add unix/gen-pass.sh: generate random passwords
-rwxr-xr-x | unix/gen-pass.sh | 81 |
1 files changed, 81 insertions, 0 deletions
diff --git a/unix/gen-pass.sh b/unix/gen-pass.sh new file mode 100755 index 0000000..4718b0c --- /dev/null +++ b/unix/gen-pass.sh @@ -0,0 +1,81 @@ +#!/bin/sh +# +# Copyright (c) 2019 Aaron LI +# MIT License +# +# Generate random passwords. +# +# Credit: +# * How to generate a random string? +# https://unix.stackexchange.com/a/230676 +# * password-store: +# http://www.passwordstore.org/ +# + +# usage: generate ${characters} ${length} +generate() { + local characters="$1" + local length="$2" + env LC_ALL=C tr -dc "${characters}" </dev/urandom | + head -c ${length} +} + +usage() { + cat << _EOF_ +Generate random passwords. + +usage: + ${0##*/} [-n] [-l length] [count] + +options: + -n : no symbols, i.e., only alphabets and numbers + -l length : password length (default: 16) + count : number of passwords to generate (default: 1) +_EOF_ + + exit 1 +} + +main() { + local characters="[:graph:]" + local length=16 + local count=1 + + while getopts :hl:n opt; do + case ${opt} in + h) + usage + ;; + l) + length="${OPTARG}" + ;; + n) + characters="[:alnum:]" + ;; + \?) + echo "Invalid option -${OPTARG}" + usage + ;; + :) + echo "Option -${OPTARG} requires an argument" + usage + ;; + esac + done + + shift $((${OPTIND} - 1)) + if [ $# -eq 0 ]; then + : + elif [ $# -eq 1 ]; then + count="$1" + else + usage + fi + + for i in $(seq ${count}); do + generate "${characters}" ${length} + echo + done +} + +main "$@" |