Snippets

Kunzhipeng Python版本的Squid3.5权限认证脚本模板

Created by Qi Peng
# coding: utf-8
# squid_auth_helper.py
# Author: redice(qi@site-digger.com)
# Created at: 2016-10-12
# Python版本的Squid3.5权限认证脚本模板
# 在squid.conf中的"htcp_access deny all"之前加入如下配置:
# auth_param basic program /usr/bin/python /etc/squid/squid_auth_helper.py
# auth_param basic key_extras "%>a %la"
# auth_param basic realm IPRENT.CN Proxy Auth Required
# acl auth_users proxy_auth REQUIRED
# http_access allow auth_users
# 上面第二行的功能是将“客户端IP”和“服务端IP”作为命令行参数传递给认证脚本。支持更多宏格式http://devel.squid-cache.org/customlog/logformat.html
# key_extras是Squid3.5版本添加的新特性(老版本不支持),详见http://wiki.squid-cache.org/Squid-3.5


import sys
import logging

# 记录日志
# sudo chmod 755 /var/log/squid/squid_auth_helper.log
# sudo chown proxy:proxy /var/log/squid/squid_auth_helper.log
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename='/var/log/squid/squid_auth_helper.log', filemode='a')
    
def matchpasswd(username, password, client_ip, local_ip):
    """检测是否有权限访问
    """
    logging.info('New auth request: username = {}, password = {}, client_ip = {}, local_ip = {}'.format(username, password, client_ip, local_ip))
    # 这里仅实现了一个最简单的判断。你可以结合数据库实现复杂的认证逻辑。
    # 可以根据client_ip和local_ip做一些高级的限制,比如限制一个账号只能使用服务器上的某些IP(考虑多IP服务器情况)。
    if username == 'test' and password == 'iprent.cn':
        return True
    return False

if __name__ == '__main__':
    while True:
        # 从stdin读取一行
        line = sys.stdin.readline()
        # 提取username, password, client ip, local ip参数
        username, password, client_ip, local_ip = line.split()
        # 判断是否有权限
        if matchpasswd(username, password, client_ip, local_ip):
            sys.stdout.write('OK\n')
        else:
            sys.stdout.write('ERR\n')
        # 输出
        sys.stdout.flush()

Comments (0)