需求
- 有时,我需要通过 IP + 端口的方式来访问服务,而不是所有服务都需要通过域名反向代理。
- 但我需要确保禁止其他 IP 访问我的端口。
- 这时,白名单方法就显得尤为重要。
脚本(非 Docker 服务)
如果你不使用 Docker,可以通过以下脚本进行操作:
curl -sS -O https://raw.githubusercontent.com/woniu336/open_shell/main/ipwl.sh && chmod +x ipwl.sh && ./ipwl.sh
如果遇到错误提示,可以执行以下命令解决:
sudo mkdir -p /etc/mysql
sudo touch /etc/mysql/mariadb.cnf
sudo dpkg --configure -a
查看
sudo iptables -S INPUT
amh面板设置方法,例如29669端口
- 首先创建一个新的 ipset 用于 29669 端口的白名单:
sudo ipset create whitelist_port_29669 hash:ip
- 向白名单中添加您想要允许的 IP 地址,例如:
sudo ipset add whitelist_port_29669 8.8.8.8 # 替换为您想要允许的 IP 地址
- 查看规则
sudo iptables -L INPUT --line-numbers
- 移除对 29669 端口的通用许可,假设在32编号
sudo iptables -D INPUT 32
- 然后添加新规则,允许 HTTP 端口和 29670端口的访问(与原始规则相同,但不包括 29669 ):
sudo iptables -I INPUT 32 -p tcp -m multiport --dports 80,29670 -j ACCEPT
- 最后,添加针对 29669 端口的白名单规则:
sudo iptables -I INPUT 33 -p tcp -m tcp --dport 29669 -m set --match-set whitelist_port_29669 src -j ACCEPT
sudo iptables -I INPUT 34 -p tcp -m tcp --dport 29669 -j DROP
- 保存规则,确保重启后规则仍然生效:
sudo iptables-save > /etc/iptables/rules.v4
如果将来需要添加更多 IP 到白名单,只需使用:
sudo ipset add whitelist_port_29669 新IP地址
这样的修改将确保只有在白名单中的 IP 地址才能访问 29669 端口,而其他 IP 地址的访问将被拒绝。
Docker 部署
对于使用 Docker 部署的服务,步骤如下:
- 安装 ipset(如果尚未安装):
sudo apt-get update
sudo apt-get install ipset -y
- 创建允许访问的特定 IP 集合:
sudo ipset create allowed_ips hash:ip
- 添加需要允许访问的特定 IP 地址:
sudo ipset add allowed_ips 192.168.1.11
- 添加 iptables 规则以允许指定端口访问,以 9000 端口为例:
sudo iptables -I DOCKER-USER 1 -m set --match-set allowed_ips src -p tcp --dport 9000 -j ACCEPT
sudo iptables -I DOCKER-USER 2 -p tcp --dport 9000 -j DROP
如果要添加新的ip白名单,例如放行192.168.2.22
sudo ipset add allowed_ips 192.168.2.22