微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

linux-Bash脚本,需要帮助循环

目前,我正在使用此脚本来阻止中国的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

更新

根据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 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐