[英]Bash script, need help for loop
目前我正在使用此脚本阻止中国的IP地址:
# Create the ipset list
ipset -N china hash:net
# remove any old list that might exist from previous runs of this script
rm cn.zone
# Pull the latest IP set for China
wget -P . http://www.ipdeny.com/ipblocks/data/countries/cn.zone
# Add each IP address from the downloaded list into the ipset 'china'
for i in $(cat ./cn.zone ); do ipset -A china $i; done
# Restore iptables
/sbin/iptables-restore < /etc/iptables/rules.v4
这工作正常,但我如何在多个国家/地区使用它?
我试过这个,但它不起作用:
ipset -N blockall hash:net
rm blockall.zone
for i in $(wget -P . http://www.ipdeny.com/ipblocks/data/countries/{cn,in,iq,af,ir,ae,sg,hk,kw,kg}.zone);
do ipset -A blockall $i; done
/sbin/iptables-restore < /etc/iptables/rules.v4
UPDATE
根据Agnul的回答,我尝试了这个:
rm blockall.zone
# pull files for each country
wget -P . http://www.ipdeny.com/ipblocks/data/countries/{cn,in,iq,af,ir,ae,sg,hk,kw,kg}.zone
# for each country file
for c in *.zone; do
#for each line in country
while read i; do
ipset -A blockall $i;
done <"$c"
done
然后我chmod
我的脚本
chmod +x /etc/block-blockall.sh
但是,它不会创建文件blockall.zone
或单数文件*.zone
。
假设第一个脚本,中国的那个,正在做你期望的,试试这个来处理几个国家:
#!/bin/bash
COUNTRIES="cn in iq af ir ae sg hk kw kg"
ipset -N blockall hash:net
for country in $COUNTRIES; do
wget -O - http://www.ipdeny.com/ipblocks/data/countries/$country.zone 2>/dev/null | while read ip; do
ipset -A blockall $ip;
done
done
/sbin/iptables-restore < /etc/iptables/rules.v4
注意不需要也不使用临时文件。
如果出于任何原因需要临时文件,请使用:
#!/bin/bash
COUNTRIES="cn in iq af ir ae sg hk kw kg"
ZONEFILE=blockall.zone
rm -f $ZONEFILE
ipset -N blockall hash:net
for country in $COUNTRIES; do
wget -O - http://www.ipdeny.com/ipblocks/data/countries/$country.zone 2>/dev/null >> $ZONEFILE
done
while read ip; do
ipset -A blockall $ip;
done < $ZONEFILE
/sbin/iptables-restore < /etc/iptables/rules.v4
就像是
# pull files for each country
wget -P . http://www.ipdeny.com/ipblocks/data/countries/{cn,in,iq,af,ir,ae,sg,hk,kw,kg}.zone
# for each country file
for c in *.zone; do
#for each line in country
while read i; do
ipset -A blockall $i;
done <"$c"
done
应该管用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.