executable_genpass
2538 bytes
1#!/usr/bin/bash
2
3function usage()
4{
5 local just_help=$1
6 local missing_required=$2
7 local invalid_argument=$3
8 local invalid_option=$4
9
10 local help="Usage: genpass -c COUNT [OPTION] [SET]
11
12Generate random password from /dev/urandom using the character set chosen
13
14Option (pick one character set):"
15local help_options="\t\-a ,\--all\ all printable characters, not including space
16 \t\-lt ,\--limited\ all except special characters [A-Za-z0-9%+,-./:=@^_]
17 \t\-b32 ,\--base32\ all valid base32 characters [A-Z2-7=]
18 \t\-b64 ,\--base64\ all valid base64 characters [A-Za-z0-9+/]
19 \t\-an ,\--alphanumeric\ letters and digits
20 \t\-al ,\--alpha\ letters
21 \t\-u ,\--upper\ upper case letters
22 \t\-l ,\--lower\ lower case letters
23 \t\-n ,\--numeric\ digits
24 \t\-h ,\--hex\ hexadecimal digits
25 \t\-c ,\--count <length>\ Length of password to generate
26 \t\[SET]\ \ Other character SET compatible with tr
27"
28
29 if [ "$missing_required" != "" ]
30 then
31 echo "Missing required argument: $missing_required"
32 fi
33
34 if [ "$invalid_option" != "" ] && [ "$invalid_value" = "" ]
35 then
36 echo "Invalid option: $invalid_option"
37 elif [ "$invalid_value" != "" ]
38 then
39 echo "Invalid value: $invalid_value for option: --$invalid_option"
40 fi
41
42 echo -e "
43"
44 echo "$help"
45 echo "$help_options" | column -t -s'\'
46 return
47}
48function init_args()
49{
50REQ_ARGS=("count" )
51
52# get command line arguments
53POSITIONAL=()
54while [[ $# -gt 0 ]]
55do
56key="$1"
57
58case $key in
59 -a|--all)
60 characters="[:graph:]"
61 shift
62 ;;
63 -lt|--limited)
64 characters="A-Za-z0-9%+,-./:=@^_"
65 shift
66 ;;
67 -b32|--base32)
68 characters="A-Z2-7="
69 shift
70 ;;
71 -b64|--base64)
72 characters="A-Za-z0-9+/"
73 shift
74 ;;
75 -an|--alphanumeric)
76 characters="[:alnum:]"
77 shift
78 ;;
79 -al|--alpha)
80 characters="[:alpha:]"
81 shift
82 ;;
83 -u|--upper)
84 characters="[:upper:]"
85 shift
86 ;;
87 -l|--lower)
88 characters="[:lower:]"
89 shift
90 ;;
91 -n|--numeric)
92 characters="[:digit:]"
93 shift
94 ;;
95 -h|--hex)
96 characters="0-9a-f"
97 shift
98 ;;
99 -c|--count)
100 count="$2"
101 shift 2
102 ;;
103 *)
104 POSITIONAL+=("$1") # saves unknown option in array
105 shift
106 ;;
107esac
108done
109
110for i in "${REQ_ARGS[@]}"; do
111 # $i is the string of the variable name
112 # ${!i} is a parameter expression to get the value
113 # of the variable whose name is i.
114 req_var=${!i}
115 if [ "$req_var" = "" ]
116 then
117 usage "" "--$i"
118 exit
119 fi
120done
121}
122
123init_args $@
124
125if [ -z $characters ]; then
126 if [ -z $POSITIONAL ]; then
127 echo "Missing at least one character set"
128 exit 2
129 else
130 characters=$POSITIONAL
131 fi
132fi
133
134< /dev/urandom tr -dc $characters | head -c $count