我可以为Flask提供IP白名单范围,而不是IP列表吗?

时间:2019-04-21 16:35:30

标签: python flask

我有一个基本的烧瓶服务器,正在使用Google Chat Bot进行Python开发。我想将可以访问服务器的IP范围限制在一定范围内。为此,请说123.0.0.1至123.255.255.255。

从网上看到的类似问题中,我知道如何轻松地针对单个IP做到这一点。

从烧瓶导入中止,请求

@app.before_request
def limit_remote_addr():
    if request.remote_addr != '123.0.0.1':
        abort(403)  # Forbidden

但是我不想为每个IP都这样做,也不必列出清单。那可能吗?还是我最好配置防火墙以删除此步骤?

1 个答案:

答案 0 :(得分:0)

正如@Klaus D.所述,您可以检查远程地址是否以该地址的一部分开头。

您可以检查远程地址是否在@before_request装饰器中的特定IP地址列表中列出。

这里我展示了一个在Python中白名单IP地址的示例。

使用本地网络(通过WiFi连接)进行测试。

Flask服务器的本地IP地址:192.168.0.107

app.py

from flask import abort, Flask, render_template, request


ALLOWED_IPS = ['192.168.1.', '127.0.0.1']

app = Flask(__name__)

@app.errorhandler(403)
def permission_error(e):
    return render_template('403.html', error_code=403), 403

@app.before_request
def limit_remote_addr():
    client_ip = str(request.remote_addr)
    valid = False
    for ip in ALLOWED_IPS:
        if client_ip.startswith(ip) or client_ip == ip:
            valid = True
            break
    if not valid:
        abort(403)


@app.route('/', methods = ['GET'])
def home():
    return "Your IP: {}".format(request.remote_addr)

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

403.html

<h3>Your IP address is not white listed</h3>

输出:

从不在ALLOWED_IPS列表中的IP访问应用程序:

blocked IP

ALLOWED_IPS列表中的IP访问应用程序:

white listed IP

ALLOWED_IPS列表更新为ALLOWED_IPS = ['192.168.0.', '127.0.0.1']之后,我可以从192.168.0.107访问Flask应用程序:

valid IP