linux中禁止访问外网部分ip或网址

背景:

  服务中调用了外部的接口,需要模拟网络不通的情况,验证程序因为网络不通不能成功调用外部接口的场景。

方法:

  修改iptables文件,见注释描述

# Generated by iptables-save v1.4.21 on Mon Mar  9 12:05:45 2020
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [723:227286]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited



#限制访问某个外网URL,取消限制后需要重启iptables服务service iptables restart
#限制网址,默认端口80
#-A OUTPUT -p tcp -d www.baidu.com --dport 80 -j DROP
#限制ip+端口
#-A OUTPUT -p tcp -d 120.**.**.*** --dport 8090 -j DROP
COMMIT
# Completed on Mon Mar  9 12:05:45 2020

限制和取消后都需要重启iptables服务:service iptables restart

测试:

  封锁前:

  

 

  禁用后:

  没有任何返回

  

 

posted @ 2020-03-09 15:07  秋寻草  阅读(10345)  评论(0编辑  收藏  举报