linux 下经常需要生成用 htpaswd 加密的账户数据,这个工具在 apache2-utils 里,可是现在大部分都用 nginx 了,于是从网上找了个编写的 shell 脚本来实现这个功能,输入用户名和密码并指定要存放的文件路径和名称即可。

原始脚本来自于 http://www.lnmp.org ,作者 licess ,在此表示感谢!

代码:

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
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH`

echo "====================================="
echo "# A tool like htpasswd for Nginx #"
echo "#-----------------------------------#"
echo "# Author:Licess http://www.lnmp.org #"
echo "====================================="

#set UserName

username=""
read -p "Please input UserName:" username
if [ "$username" = "" ]; then
echo "Error:UserName can't be NULL!"
exit 1
fi
echo "==========================="
echo "UserName was: $username"
echo "==========================="

#set password

unpassword=""
read -p "Please input the Password:" unpassword
if [ "$unpassword" = "" ]; then
echo "Error:Password can't be NULL!"
exit 1
fi
echo "==========================="
echo "Password was: $unpassword"
echo "==========================="
password=$(perl -e 'print crypt($ARGV[0], "pwdsalt")' $unpassword)

#set htpasswd file

htfile=""
read -p "Please input Auth filename with absorlute path:" htfile
if [ "$htfile" = "" ]; then
echo "Error:Auth filename can't be NULL!"
exit 1
fi
echo "==========================="
echo "Auth File: $htfile"
echo "==========================="

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
}
echo ""
echo "Press any key to Creat...or Press Ctrl+c to cancel"
char=`get_char`

if [ ! -f $htfile.conf ]; then
echo "Create Auth file......"
cat >$htfile<<eof
$username:$password
eof
echo "Create Auth file successful,auth file path:$htfile."
else
echo "File already exists,please run this script again."
exit 1
fi