-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
openssl-htpasswd
executable file
·70 lines (60 loc) · 1.26 KB
/
openssl-htpasswd
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
#!/bin/bash
#
print_help()
{
echo "$(basename \"$0\") [-Dci] passwdfile username [password]"
echo -e "\t-D delete given user"
echo -e "\t-c truncate file (will contain only new user"
echo -e "\t-i read password from stdin"
echo -e "\t-h print this help"
}
ensure_pwd()
{
[ "$STDIN" = 1 ] && read -s PWD
[ -z "$PWD" ] && echo "missing or empty password" >&2 && print_help >&2 && exit 1
PWD=$(openssl passwd -crypt "$PWD")
}
action="modify"
while getopts "Dcid" arg; do
case $arg in
D)
action="delete"
;;
c)
action="create"
;;
i)
STDIN=1
;;
*)
echo "invalid usage" >&2
print_help >&2
exit 1
;;
esac
done
shift $(($OPTIND - 1))
FILE="$1"
USER="$2"
PWD="$3"
[ -z "$USER" ] && echo "missing username" >&2 && print_help >&2 && exit 1
[ -z "$FILE" ] && echo "missing filename" >&2 && print_help >&2
case "$action" in
delete)
[ ! -f "$FILE" ] && exit 0
tmp=$(mktemp)
grep -v "^$USER:" "$FILE" > "$tmp"
cat "$tmp" > "$FILE" && rm "$tmp" && exit 0
;;
create)
ensure_pwd
echo "$USER:$PWD" > "$FILE" && exit 0
;;
modify)
ensure_pwd
tmp=$(mktemp)
(grep -v "^$USER:" "$FILE" 2>/dev/null; echo "$USER:$PWD") > "$tmp" && cat "$tmp" > "$FILE" && rm "$tmp" && exit 0
;;
esac
# should not reach here
exit 1