我有一个基本的烧瓶服务器,用于使用Google Chat Bot进行Python开发。我想将可以访问服务器的IP范围限制在一定范围内。出于此目的,例如123.0.0.1至123.255.255.255。
从网上看到的类似问题我知道如何轻松地为单个IP做这件事。
从flask导入中止,请求
@app.before_request
def limit_remote_addr():
if request.remote_addr != '123.0.0.1':
abort(403) # Forbidden
但我不想为每个IP做这个,或者必须列出一个列表。那可能吗?或者我最好配置防火墙以删除此步骤?
正如@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访问应用程序:
从ALLOWED_IPS
列表中的IP访问应用程序:
将ALLOWED_IPS
列表更新为ALLOWED_IPS = ['192.168.0.', '127.0.0.1']
后,我可以从192.168.0.107
访问Flask应用程序: