nginx网站加密认证

Posted on Posted in nginx
Tips: 本文创建于2014年12月17日,已超过 2 年,内容或图片可能已经失效!

jiamirenzheng

与apache的访问需要密码一样

1、nginx配置

在需要加密的路径配置中,加入两句

location / {
	auth_basic "Password please"; #这里提示语
	auth_basic_user_file /etc/nginx/passwd/password; #用户和密码的加密文件路径
        }

如果整个访问目录都需要密码访问,把两句话放在location的外层即可

2、生成加密文件password

密码文件的格式为:user:password(password为加密后的密码串)

方法一:用apache自带的htpasswd命令
htpasswd -c -d password user1
# 回车输入密码,-c表示生成文件,-d表示用crypt加密
方法二:利用perl脚本
#!/usr/bin/perl
use strict;
my $passWord = $ARGV[0];
print crypt($passWord,$passWord)."\n";

把上面的脚本保存为create.pl,执行脚本生成密码

perl create.pl password(换成你自己的密码)

执行后,会输出password的加密后的密码,然后把用户名和密码按照密码文件的格式写一起

方法三:利用python脚本

点击网址

脚本

#!/usr/bin/python
"""Replacement for htpasswd"""
# Original author: Eli Carter

import os
import sys
import random
from optparse import OptionParser

# We need a crypt module, but Windows doesn't have one by default.  Try to find
# one, and tell the user if we can't.
try:
    import crypt
except ImportError:
    try:
        import fcrypt as crypt
    except ImportError:
        sys.stderr.write("Cannot find a crypt module.  "
                         "Possibly http://carey.geek.nz/code/python-fcrypt/\n")
        sys.exit(1)


def salt():
    """Returns a string of 2 randome letters"""
    letters = 'abcdefghijklmnopqrstuvwxyz' \
              'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \
              '0123456789/.'
    return random.choice(letters) + random.choice(letters)


class HtpasswdFile:
    """A class for manipulating htpasswd files."""

    def __init__(self, filename, create=False):
        self.entries = []
        self.filename = filename
        if not create:
            if os.path.exists(self.filename):
                self.load()
            else:
                raise Exception("%s does not exist" % self.filename)

    def load(self):
        """Read the htpasswd file into memory."""
        lines = open(self.filename, 'r').readlines()
        self.entries = []
        for line in lines:
            username, pwhash = line.split(':')
            entry = [username, pwhash.rstrip()]
            self.entries.append(entry)

    def save(self):
        """Write the htpasswd file to disk"""
        open(self.filename, 'w').writelines(["%s:%s\n" % (entry[0], entry[1])
                                             for entry in self.entries])

    def update(self, username, password):
        """Replace the entry for the given user, or add it if new."""
        pwhash = crypt.crypt(password, salt())
        matching_entries = [entry for entry in self.entries
                            if entry[0] == username]
        if matching_entries:
            matching_entries[0][1] = pwhash
        else:
            self.entries.append([username, pwhash])

    def delete(self, username):
        """Remove the entry for the given user."""
        self.entries = [entry for entry in self.entries
                        if entry[0] != username]


def main():
    """%prog [-c] -b filename username password
    Create or update an htpasswd file"""
    # For now, we only care about the use cases that affect tests/functional.py
    parser = OptionParser(usage=main.__doc__)
    parser.add_option('-b', action='store_true', dest='batch', default=False,
        help='Batch mode; password is passed on the command line IN THE CLEAR.'
        )
    parser.add_option('-c', action='store_true', dest='create', default=False,
        help='Create a new htpasswd file, overwriting any existing file.')
    parser.add_option('-D', action='store_true', dest='delete_user',
        default=False, help='Remove the given user from the password file.')

    options, args = parser.parse_args()

    def syntax_error(msg):
        """Utility function for displaying fatal error messages with usage
        help.
        """
        sys.stderr.write("Syntax error: " + msg)
        sys.stderr.write(parser.get_usage())
        sys.exit(1)

    if not options.batch:
        syntax_error("Only batch mode is supported\n")

    # Non-option arguments
    if len(args) < 2:
        syntax_error("Insufficient number of arguments.\n")
    filename, username = args[:2]
    if options.delete_user:
        if len(args) != 2:
            syntax_error("Incorrect number of arguments.\n")
        password = None
    else:
        if len(args) != 3:
            syntax_error("Incorrect number of arguments.\n")
        password = args[2]

    passwdfile = HtpasswdFile(filename, create=options.create)

    if options.delete_user:
        passwdfile.delete(username)
    else:
        passwdfile.update(username, password)

    passwdfile.save()


if __name__ == '__main__':
    main()

执行脚本

python htpasswd.py -c -b passwd username password

passwd为生成的文件,后面两个为用户名和密码

方法四:bash脚本(和perl一样)
#!/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 "====================================="

#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(文件名):" htfile
	if [ "$htfile" = "" ]; then
		echo "Error:Auth filename can't be NULL!"
		exit 1
	fi

	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`
echo $username:$password >> $htfile

 

3、添加多用户

去掉上面的 -c 参数即可

方法

echo crypt('123', base64_encode('123'));

» 转载请注明来源:若我若鱼 » nginx网站加密认证

Leave a Reply

Your email address will not be published. Required fields are marked *

fourteen − 13 =