Passwortgenerator

Aus wiki.archlinux.de
Version vom 4. März 2014, 01:04 Uhr von Kerberos (Diskussion | Beiträge) (Skript um eine Hilfefunktion erweitert und eine Absicherung gegen Fehleingaben eingebaut.)
Zur Navigation springen Zur Suche springen

Ein "einfacher" Passwortgenerator

#!/bin/bash

# Generate a random password
#
# $1 number of characters; defaults to 20
#
# $2 charset
# 0 = special characters, numbers and letters (default)
# 1 = numbers and letters
# 2 = letters only
# 3 = numbers only
#
#
# usage: pwgen.sh <LENGTH> <CHARS>
#
# examples:
# 
# length = 20, special characters, numbers and letters
# pwgen.sh
#
# length = 10, special characters, numbers and letters
# pwgen.sh 10
#
# length = 8, numbers and letters
# pwgen.sh 8 1
#
# length = 25, letters only
# pwgen.sh 25 2


_helptext_()
{
    echo
    echo "\"pwgen.sh\" generate a random password."
    echo "usage: pwgen.sh [LENGTH CHARS] [-h]"
    echo
    echo "LENGTH		number of characters; default is 20"
    echo "CHARS		0 = special characters, numbers and letters (default)"
    echo "		1 = numbers and letters"
    echo "		2 = letters only"
    echo "		3 = numbers only"
    echo "-h		Show this text"
    echo
    echo "If one introduces \"pwgen.sh\" from without \"[LENGTH CHARS]\", then the default values are used."
    echo
    echo "Examples:"
    echo
    echo "\"pwgen.sh\" OR \"pwgen.sh 20 0\""
    echo "   length:	20 characters"
    echo "   charset:	special characters, numbers and letters"
    echo "   example:	"`cat /dev/urandom | tr -dc [:graph:] | head -c 20`
    echo
    echo "pwgen.sh 10"
    echo "   length:	10 characters"
    echo "   charset:	special characters, numbers and letters"
    echo "   example:	"`cat /dev/urandom | tr -dc [:graph:] | head -c 10`
    echo
    echo "pwgen.sh 8 1"
    echo "   length:	8 characters"
    echo "   charset:	numbers and letters"
    echo "   example:	"`cat /dev/urandom | tr -dc [:alnum:] | head -c 8`
    echo
    echo "pwgen.sh 25 2"
    echo "   length:	25 characters"
    echo "   charset:	letters only"
    echo "   example:	"`cat /dev/urandom | tr -dc [:alpha:] | head -c 25`
    echo
    echo "pwgen.sh 4 3"
    echo "   length:	4 characters"
    echo "   charset:	numbers only"
    echo "   example:	"`cat /dev/urandom | tr -dc [:digit:] | head -c 4`
    echo
    exit 0
}


_invalid_()
{
    echo
    echo "Invalid input. For more information use"
    echo "   pwgen.sh -h"
    echo
    exit 1
}


if [ "$1" = "" ]; then
    LENGTH=20
elif [ "$1" = "-h" ]; then
    _helptext_
elif [[ `echo "$1" | grep -E ^[[:digit:]]+$` ]]; then
    LENGTH=$1
else
    _invalid_
fi


case $2 in
    "") CHARS="[:graph:]" ;;
    0) CHARS="[:graph:]" ;;
    1) CHARS="[:alnum:]" ;;
    2) CHARS="[:alpha:]" ;;
    3) CHARS="[:digit:]" ;;
    *) _invalid_ ;;
esac

echo
cat /dev/urandom | tr -dc $CHARS | head -c $LENGTH
echo
echo