Currently I'm using this script to block China's IP address:
# 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
This works fine but how can I use it with multiple countries?
I tried this but it doesn't work:
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
Based on Agnul's answer, I tried this:
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
Then I chmod
my script
chmod +x /etc/block-blockall.sh
However it doesn't create the file blockall.zone
or singular file *.zone
as it should.
Assuming the first script, china's one, is doing what you expect, try this one to handle several countries:
#!/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
note temporary file is not need nor used.
If, for any reason, the temporary file is need, use:
#!/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