Shell Script Generate htpasswd.sh


常用到.所以寫成 Script.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/bin/bash

username=""
password=""
savefile=""
filepath=""

RESET='\033[0m'
RED='\033[00;31m'
GREEN='\033[00;32m'
YELLOW='\033[00;33m'
BLUE='\033[00;34m'
PURPLE='\033[00;35m'
CYAN='\033[00;36m'
LIGHTGRAY='\033[00;37m'

get_char() {
SAVEDSTTY=`stty -g`
stty -echo
stty cbreak
dd if=/dev/tty bs=1 count=1 2> /dev/null
stty -raw
stty echo
stty $SAVEDSTTY
}

error() {
echo -e "${RED}$1${RESET}"
}

success() {
echo -e "${GREEN}$1${RESET}"
}

read -p "Please enter username: " username

if [ "$username" = "" ]; then
error "Error: Username cannot empty"
exit 1
fi

read -p "Please enter password: " password

if [ "$password" = "" ]; then
error "Error: Password cannot empty"
exit 1
fi

read -p "Need save to htpaaswd file (Y/N)? " savefile

if [ "$savefile" = "Y" ] || [ "$savefile" = "y" ]; then
read -p "Please enter htpasswd file path: " filepath
fi

encrypted=$(perl -e 'print crypt($ARGV[0], time())', $password)

success "Your username: $username"
success "Your password: $password"
success "Output string: $username:$encrypted"

if [ "$filepath" != "" ]; then
echo ""
echo "Press any key to Create file or Press Ctrl+c to cancel"
echo ""
char=`get_char`

if [ ! -f "$filepath" ]; then
success "Save to file: $filepath"
echo "$username:$encrypted" >> $filepath
else
error "Error: File already exists"
exit 1
fi
fi