此处以samba服务为例
#!/bin/bash
# chkconfig: 2345 10 90
# description: iptables ctrl
export_path=/usr/local/iptables_ctrl.sh
function start_iptables_ctrl() {
# start iptables
iptables_status=$(systemctl status iptables | grep 'Active' | awk '{print $2}')
if [[ ( -n $iptables_status ) && $iptables_status -eq 'Active' ]]; then
echo "iptables started"
else
systemctl enable iptables
systemctl start iptables
echo "iptables restart"
fi
sleep 30
echo `iptables -nL | grep 'Chain DBAAS'`
iptables -t filter -N DBAAS # 创建DBaas链
iptables -t filter -I INPUT -j DBAAS # 关联DBaas链
iptables -I DBAAS -p tcp --dport 139 -j DROP # 拒绝所有主机访问本机 tcp/udp xx 端口
iptables -I DBAAS -p tcp --dport 445 -j DROP # 拒绝所有主机访问本机 tcp/udp xx 端口
iptables -I DBAAS -p udp --dport 137 -j DROP # 拒绝所有主机访问本机 tcp/udp xx 端口
iptables -I DBAAS -p udp --dport 138 -j DROP # 拒绝所有主机访问本机 tcp/udp xx 端口
ips=($(ip addr | grep -v inet6 | grep inet | awk '{print $2}'))
for i in ${ips[@]} ; do
echo $i
ip1=$i
ip1g=`echo $ip1 | awk -F '/' '{print $2}'`
ip1cal=`ipcalc -n $ip1 | awk -F '=' '{print $2}'`
ipresp=$ip1cal"/"$ip1g
echo $ipresp
iptables -I DBAAS -s $ipresp -p tcp --dport 139 -j ACCEPT # 配置允许某一网段访问本机所有端口
iptables -I DBAAS -s $ipresp -p tcp --dport 445 -j ACCEPT # 配置允许某一网段访问本机所有端口
iptables -I DBAAS -s $ipresp -p udp --dport 138 -j ACCEPT # 配置允许某一网段访问本机所有端口
iptables -I DBAAS -s $ipresp -p udp --dport 137 -j ACCEPT # 配置允许某一网段访问本机所有端口
done
echo "config iptables success!"
# start check task
# sed -n '/start_iptables_ctrl.sh/p' /var/spool/cron/root |grep start_iptables_ctrl.sh
# let res=$?
# if [[ $res = 1 ]]; then
# echo "* * * * * ${export_path}/start_iptables_ctrl.sh" >> /var/spool/cron/root
# fi
}
function main() {
start_iptables_ctrl
}
main "$@"
exit $?
cd /etc/init.d
vi servicename # 此步骤千万不要带文件后缀,这里只有服务名称,这里服务名称使用iptablesctrl,将脚本复制进来
chmod 755 servicename
chkconfig servicename on
reboot # 重启检查是否执行
iptables -nL # 查看规则添加情况
iptables -F DBAAS # 删除规则(此处仅记录经常使用命令,非必要执行)