1

I have a log file like this :

Frq:15 IP:0.0.0.0 Date: 2014-03-21 12:19:31 AM
Frq:9 IP:198.252.206.25 Date: 2014-03-21 12:19:31 AM

Now i get column of ip addresses with awk :

cat /tmp/test | awk '{print $2}'|awk '{gsub("IP:", "");print}' 

And the result is :

0.0.0.0
198.252.206.25

I want add this ip addresses into iptables to be DROP from INPUT but i dont know how

Thanks friends.

6
  • I used awk '{gsub("IP:", "");print}' to remove IP: Mar 20, 2014 at 21:07
  • 3
    Save a cat. awk '{print $2}'|awk '{gsub("IP:", "");print}' /tmp/test Mar 20, 2014 at 21:30
  • 4
    Lets just hope you dont have 127.0.0.1 in there.. Mar 20, 2014 at 21:42
  • Why are people downvoting this question?
    – opsguy
    Mar 20, 2014 at 21:43
  • 1
    @AaronCopley: +1, but save an awk, too, as in opsguy's answer - or: awk -F '[: ]' '{print $4}' Mar 21, 2014 at 1:15

3 Answers 3

1

My attempt:

awk '{sub("IP:", "", $2); print $2}' /tmp/test | xargs -n1 -I{} iptables -A INPUT -s {} -j DROP
0
6

You'll be farther ahead by extending fail2ban by dropping in a custom configuration file into its .d config directory.

Do as little work as possible!

1

You could just write a script that will loop over your awk result and creates appropriate iptables rules on the fly :

#!/bin/sh

cat /tmp/test | awk '{print $2}'|awk '{gsub("IP:", "");print}' | while read IP
do
  iptables -A INPUT -s $IP -j DROP
done

However, i don't know your context and how your log file can be trusted, but it is dangerous and you should survey which IPs you are dropping.

For a sample, the following makes an exception for 127.0.0.1 :

#!/bin/sh

cat /tmp/test | awk '{print $2}'|awk '{gsub("IP:", "");print}' | while read IP
do
  if [ "$IP" != "127.0.0.1" ]; then
    iptables -A INPUT -s $IP -j DROP
  fi
done

Not the answer you're looking for? Browse other questions tagged .