采用flask制作web页面管理nginx配置的IP白名单

行云流水
2022-04-06 / 2 评论 / 747 阅读 / 正在检测是否收录...

前言

公司内部有一个平时用的测试系统,提供给客户做体验,只有简单的几个页面用来测试功能使用,也没有注册验证。最近发现有人滥用,因为调用的是正式的接口,造成了一定的混乱。于是通过nginx访问配置了IP访问白名单。问题又来了,业务那边每次找我添加白名单IP,更烦人了。于是写了web页面,用来控制nginx访问的白名单。让他们自己去添加,世界清静了...

获取项目代码

传送门

启动

tar xvf nginx-etcmanager.tgz -C /opt/nginx-proxy/
cd /opt/nginx-proxy/nginx-etcmanager/
screen python3 main.py

设置计划任务

每到整点,所有申请的白名单IP全部过期

0 * * * * flock -xn /tmp/reset_nginx.lock -c 'cd /opt/nginx-proxy/ && sh reset_nginx.sh'

使用

web浏览器访问
http://ip:3002

说明

核心函数

@app.route('/api/addip', methods=['GET'])
def add_ip():
    """
    更新节点IP函数
    """
    if request.method == 'GET':
        info = request.values
        newip = info.get('newip', False)
        customer = info.get('customer', False)

    if not is_ipv4(newip):
        return jsonify({'msg': '输入IP非法', 'code': 1001})

    #获取IP地址列表
    h_list = get_ip_history()
    expired ="{}:00".format((datetime.datetime.now() + datetime.timedelta(hours=+1)).strftime("%Y-%m-%d  %H"))

    for item in h_list:
        jlist = item.split(",")
        if newip == item[0] and expired == item[1]:
            return jsonify({'msg': '当前IP可以直接访问,不用更新!', 'code': 1000})

    newip_str = "{},{},{}\n".format(newip, expired, customer)

    #更新nginx配置
    cmd = "sed -i '/allow 127.0.0.1;/i\ \ \ \ allow  {};' ../conf/nginx.conf && cd /opt/nginx-proxy/ && docker-compose restart".format(newip)
    status  = os.system(cmd)

    if status == 0:
        with open('./data/ip_list', 'a+') as fw:
            fw.write(newip_str)
        return jsonify({'msg': '更新成功', 'code': 1000})

    return jsonify({'msg': '更新失败', 'code': 1001})

评论 (2)

取消
只有登录/注册用户才可评论
  1. 头像
    栽植
    中国香港特别行政区 · Windows 10 · Google Chrome
    沙发

    很好很强大

    回复
  2. 头像
    zx
    · Windows 10 · Google Chrome
    板凳

    看看

    回复