手裡幾台VPS配置iptables太繁瑣,看到了朱哥的LNMP指令碼裡有一個自動設定iptables防火牆的指令碼,借來改了一下,給需要的人用;
只提供常用連接埠的設定,如果你有特殊需求只需自行添加或減少相應的連接埠即可;
使用方法:
複製代碼 代碼如下:
chmod +x iptables.sh
./iptables.sh
設定iptables開機自動啟動:
複製代碼 代碼如下:
chkconfig --level 345 iptables on
完整Shell:
複製代碼 代碼如下:
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
function support_distro(){
if [ -z "`egrep -i "centos" /etc/issue`" ];then
echo "Sorry,iptables script only support centos system now."
exit 1
fi
}
support_distro
echo "============================iptables configure============================================"
# Only support CentOS system
# 擷取SSH連接埠
if grep "^Port" /etc/ssh/sshd_config>/dev/null;then
sshdport=`grep "^Port" /etc/ssh/sshd_config | sed "s/Port\s//g" `
else
sshdport=22
fi
# 擷取DNS伺服器IP
if [ -s /etc/resolv.conf ];then
nameserver1=`cat /etc/resolv.conf |grep nameserver |awk 'NR==1{print $2 }'`
nameserver2=`cat /etc/resolv.conf |grep nameserver |awk 'NR==2{print $2 }'`
fi
IPT="/sbin/iptables"
# 刪除已有規則
$IPT --delete-chain
$IPT --flush
# 禁止進,允許出,允許迴環網卡
$IPT -P INPUT DROP
$IPT -P FORWARD DROP
$IPT -P OUTPUT ACCEPT
$IPT -A INPUT -i lo -j ACCEPT
# 允許已建立的或相關串連的通行
$IPT -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
$IPT -A OUTPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
# 限制80連接埠單個IP的最大串連數為10
$IPT -I INPUT -p tcp --dport 80 -m connlimit --connlimit-above 10 -j DROP
# 允許80(HTTP)/873(RSYNC)/443(HTTPS)/20,21(FTP)/25(SMTP)連接埠的串連
$IPT -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
$IPT -A INPUT -p tcp -m tcp --dport 873 -j ACCEPT
$IPT -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
$IPT -A INPUT -p tcp -m tcp --dport 20 -j ACCEPT
$IPT -A INPUT -p tcp -m tcp --dport 21 -j ACCEPT
$IPT -A INPUT -p tcp -m tcp --dport 25 -j ACCEPT
# 允許SSH連接埠的串連,指令碼自動偵測目前的SSH連接埠,否則預設為22連接埠
$IPT -A INPUT -p tcp -m tcp --dport $sshdport -j ACCEPT
# 允許ping
$IPT -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
$IPT -A INPUT -p icmp -m icmp --icmp-type 11 -j ACCEPT
# 允許DNS
[ ! -z "$nameserver1" ] && $IPT -A OUTPUT -p udp -m udp -d $nameserver1 --dport 53 -j ACCEPT
[ ! -z "$nameserver2" ] && $IPT -A OUTPUT -p udp -m udp -d $nameserver2 --dport 53 -j ACCEPT
# 儲存規則並重啟IPTABLES
service iptables save
service iptables restart
echo "============================iptables configure completed============================================"