如何用shell脚本防止国外ip访问服务器,可以借用IP地址库把国外IP指导入iptables以禁止访问,有效果图 ip库:http://www.ipdeny.com/ipblocks/
shell脚本:
代码示例:
#下载ip库
#wget http://rfyiamcool.googlecode.com/files/allip.txt wget http://www.ipdeny.com/ipblocks/data/countries/cn.zone #把分号去掉 sed -i 's/;$//' allip.txt #把ip端调出来 for i in `cat cn.zone` do echo "iptables -A INPUT -s $i -j ACCEPT" >>iptables.sh done cat iptables.sh
如下图:
优化以上shell脚本,在iptables.sh前添加以下命令:
代码示例:
#!/bin/bash
ziji="222.173.13.5" iptables -F iptables -X iptables -Z iptables -t nat -F iptables -t mangle -F modprobe iptable_nat modprobe ip_nat_ftp modprobe ip_nat_irc modprobe ip_conntrack modprobe ip_conntrack_ftp modprobe ip_conntrack_irc modprobe ipt_limit modprobe ipt_recent ip_list_tot=16384 modprobe ip_conntrack hashsize=16384 echo "1024 63000" > /proc/sys/net/ipv4/ip_local_port_range echo "1" > /proc/sys/net/ipv4/tcp_tw_recycle echo "1" > /proc/sys/net/ipv4/tcp_tw_reuse echo "1" > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts echo "1" >/proc/sys/net/ipv4/conf/all/log_martians echo "1" >/proc/sys/net/ipv4/tcp_syncookies echo "2" >/proc/sys/net/ipv4/tcp_synack_retries echo "5000" >/proc/sys/net/ipv4/tcp_max_syn_backlog echo "3" >/proc/sys/net/ipv4/tcp_syn_retries echo "1" > /proc/sys/net/ipv4/tcp_tw_reuse echo "1" > /proc/sys/net/ipv4/tcp_tw_recycle echo "30" > /proc/sys/net/ipv4/tcp_fin_timeout echo "1800" > /proc/sys/net/ipv4/tcp_keepalive_time echo "1" > /proc/sys/net/ipv4/ip_forward iptables -P INPUT DROP iptables -P FORWARD ACCEPT iptables -P OUTPUT ACCEPT /sbin/iptables -t nat -P PREROUTING ACCEPT /sbin/iptables -t nat -P POSTROUTING ACCEPT iptables -A INPUT -s $ziji -j ACCEPT iptables -A INPUT -i lo -j ACCEPT iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP
效果图: |