[root@hanfeng-001 ~]# vim /usr/local/sbin/iptables.sh
添加以下内容
#! /bin/bash
ipt="/usr/sbin/iptables //这里ipt是定义个一个变量(写脚本的时候,写全局的路径,就是绝对路径,就是后面再加载它,用变量去代替,看着更加简单)
$ipt -F //清空之前的规则——>在没有 -t 指定表的时候,默认的就是filter表
$ipt -P INPUT DROP //把IPPUT的策略给扔掉
$ipt -P OUTPUT ACCEPT //把OUTPUT放行
$ipt -P FORWARD ACCEPT //把FORWARD放行
$ipt -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT //增加规则,-m --state 指定了状态,并针对这些状态放行(-m --state这种用法并不多见,但是这条规则必须写进来,目的是让相关的数据包放行)
$ipt -A INPUT -s 192.168.202.130/24 -p tcp --dport 22 -j ACCEPT //把该网段的22端口数据包放行——>这里的IP段根据自己的IP段来做实验
$ipt -A INPUT -p tcp --dport 80 -j ACCEPT //把80端口数据包放行
$ipt -A INPUT -p tcp --dport 21 -j ACCEPT //把21端口数据包放行
然后保存退出:wq
[root@hanfeng ~]# sh /usr/local/sbin/iptables.sh //执行脚本
[root@hanfeng ~]# iptables -nvL
Chain INPUT (policy DROP 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
30 2148 ACCEPT all -- * * 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
0 0 ACCEPT tcp -- * * 192.168.202.0/24 0.0.0.0/0 tcp dpt:22
0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:80
0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:21
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain OUTPUT (policy ACCEPT 18 packets, 1816 bytes)
pkts bytes target prot opt in out source destination
[root@hanfeng ~]#
[root@hanfeng-001 ~]# iptables -I INPUT -p icmp --icmp-type 8 -j DROP //会发现可ping通外面的网络,但自己的虚拟机和物理机则无法连接
[root@hanfeng-001 ~]# ping www.qq.com
PING www.qq.com (180.96.86.192) 56(84) bytes of data.
64 bytes from 180.96.86.192: icmp_seq=1 ttl=128 time=7.38 ms
64 bytes from 180.96.86.192: icmp_seq=2 ttl=128 time=6.16 ms
64 bytes from 180.96.86.192: icmp_seq=3 ttl=128 time=7.73 ms
^C
--- www.qq.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2004ms
rtt min/avg/max/mdev = 6.166/7.092/7.731/0.677 ms
[root@hanfeng-001 ~]#
[root@hanfeng ~]# iptables -D INPUT -p icmp --icmp-type 8 -j DROP
iptables: Bad rule (does a matching rule exist in that chain?).
[root@hanfeng ~]#
[root@hanfeng ~]# service iptables restart //重启iptables服务
Redirecting to /bin/systemctl restart iptables.service
[root@hanfeng ~]# iptables -nvL //这里会看到还没禁掉之前的规则
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
81 6996 ACCEPT all -- * * 0.0.0.0/0 0.0.0.0/0
0 0 ACCEPT icmp -- * * 0.0.0.0/0 0.0.0.0/0
0 0 ACCEPT all -- lo * 0.0.0.0/0 0.0.0.0/0
0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0
0 0 REJECT all -- * * 0.0.0.0/0 0.0.0.0/0
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
0 0 REJECT all -- * * 0.0.0.0/0 0.0.0.0/0
Chain OUTPUT (policy ACCEPT 61 packets, 6060 bytes)
pkts bytes target prot opt in out source destination
[root@hanfeng ~]#