Ubuntu配置防火墙,并且开机iptables自启动规则;适用于CentOS
1、登录root账号
super@super:~$ sudo passwd root
super@super:~$ su - root
以下操作可以在root下也可以在普通账号,但是ubuntu保存配置必须在root下.
每次添加或者删除规则,务必保存配置,以免丢失.
1、清空iptables所有配置(新系统操作)
sudo iptables -F
sudo iptables -X
sudo iptables -Z
2、放行SSH远程22端口及lookback规则:
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A OUTPUT -o lo -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
3、配置默认动作为拒绝,只允许流出数据:
sudo iptables --policy OUTPUT ACCEPT
sudo iptables --policy FORWARD DROP
sudo iptables -P INPUT DROP
4、配置放行的关联规则包
sudo iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A OUTPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o ens32 -j MASQUERADE
5、Ubuntu保存iptables配置与开机启动(root账号下)
super@super:~$ su - root
Password:
root@super:~
5.1、ubuntu配置规则开机自启动(可以普通账号下)
super@super:~$ more /etc/rc.local
iptables-restore < /etc/iptables-rules
exit 0
5.2 Redhat保存iptables配置
/etc/init.d/iptables save
service iptables save
延伸其他规则配置(规则保存在root账号下)
1、查看规则
super@super:~$ sudo iptables -L -n
super@super:~$ sudo iptables -nL --line-number
Chain INPUT (policy DROP)
num target prot opt source destination
1 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0
2 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:22
3 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
Chain FORWARD (policy DROP)
num target prot opt source destination
Chain OUTPUT (policy ACCEPT)
num target prot opt source destination
1 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0
2 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED
2、添加规则 (这个规则适用于第一次新规则增加,未保存之前.)
super@super:~$ sudo iptables -A INPUT -p tcp –dport 80 -j ACCEPT
3、插入规则 (适用于保存了规则之后新增规则)
super@super:~$ sudo iptables -I INPUT 2 -p tcp --dport 3306 -j ACCEPT
4、放行多个端口规则(如果插入规则,把-A换成-I)
super@super:~$ sudo iptables -A INPUT -s 172.21.16.0/24 -p tcp -m multiport –dport 8080,8081,8082 -j ACCEPT
5、对指定ip放行snmp协议
super@super:~$ sudo iptables -A INPUT -s 172.21.16.0/24 -p udp –dport 161 -j ACCEPT
6、禁止ping
super@super:~$ sudo iptables -A INPUT -p icmp –icmp-type 8 -s 0/0 -j DROP
super@super:~$ sudo iptables -A INPUT -p icmp --icmp-type 8 -s 172.21.16.18 -j ACCEPT
7、开放ping协议
super@super:~$ sudo iptables -A INPUT -p icmp -m icmp –icmp-type any -j ACCEPT
8、删除规则
super@super:~$ sudo iptables -D INPUT 2
super@super:~$ sudo iptables -D INPUT -p icmp –icmp-type 8 -s 172.21.16.18 -j DROP
所有规则改动都必须保存,不管是Redhat还是Ubuntu