我正在使用Python Flask框架开发一个网站,现在我做了一些devving,将我的更改推送到远程开发服务器.我将这个远程开发服务器设置为公开使用的网站app.run(host='0.0.0.0')
.
这很好,但我不想让其他人查看我的网站.出于这个原因,我不知何故想将我的IP列入白名单,以便开发服务器只为我自己的IP地址提供网站服务,没有响应,404或其他一些对其他IP地址无用的响应.我当然可以设置服务器使用apache或nginx来实际服务网站,但我喜欢自动重新加载网站上的代码更改以便我的网站
那么有人知道使用内置Flask开发服务器的方法吗?欢迎所有提示!
仅使用Flask的功能,您可以使用before_request()
钩子测试该request.remote_addr
属性:
from flask import abort, request @app.before_request def limit_remote_addr(): if request.remote_addr != '10.20.30.40': abort(403) # Forbidden
但在服务器上使用防火墙规则可能是更安全,更强大的选择.
请注意,如果浏览器和服务器之间存在反向代理,则可以屏蔽Remote_Addr; 要小心你如何限制这一点,不要把自己锁在外面.如果代理靠近服务器本身(如负载均衡器或前端缓存),则可以检查request.access_route
列表以访问实际的IP地址.仅在remote_addr
自身也是可信IP地址时执行此操作:
trusted_proxies = ('42.42.42.42', '82.42.82.42', '127.0.0.1') def limit_remote_addr(): remote = request.remote_addr route = list(request.access_route) while remote in trusted_proxies: remote = route.pop() if remote != '10.20.30.40': abort(403) # Forbidden
恕我直言,尽管您可以使用上述解决方案轻松实现预期的结果,但应在操作系统的网络层处理此类问题。
To deny/allow traffic from any source to an specific port on your server, it's a job for the Firewall of the Operating System. The packets and their sources (IP addresses), must be treated at the Network Layer on your Operating System, in the Kernel's Land, not passing to your application. If you don't have a Firewall running on your server, there must be configured one in order to protect your server, even though your server is not in Production yet.
Here is the train of thought: considering that the packets that are coming to your server, firstly, are passing through the analyse of the Kernel of your Operating System (suppose that you're using a Unix-like or GNU/Linux-like OS), you can deny/allow the incoming connections to the Network Layer from Kernel's Land, using a packet filtering software like Netfilter which generally is managed via IPTABLES.
Here is a Netfiler rule which attends your need:
/sbin/iptables -A INPUT -s ! your_ip_address --dport 80 -j DROP
All traffic coming to the port 80 will be dropped, EXCEPTING for the connections coming from your_ip_address.
The principle of filtering/blocking incoming connections/packets at the Network Layer of the Operating System is somewhat applied in a very similar way for the Microsoft OSes, but I'm not sure. I never researched about how Windows Firewall deals with packet filtering but there are good chances that it works in a very similar way.
So, here is a final thought:
Packets must treated at the Network Layer of your Operating System. Do not let the packets come to your application: it's safer and distributes the job to the right parties on your system.
The Linux Kernel and its modules (Netfilter) are much more reliable, competent and effective to treat this kind of issues, than Flask.
Keep in mind this good practice ;).