Question

I have a test server that is constantly receiving requests (hits) that blocks my apache server.

be blocking the ips one by one a lot of work and is impractical (iptables -I INPUT -s xxx.xxx.xxx.xxx -j DROP). what I thought was whether it would be possible to block all ips that are on the error.log file at once.

it is possible to make a script to do this?

error.log

[Fri Jan 31 02:39:54.827551 2014] [:error] [pid 2442] [client 198.98.104.231:2078] script '/var/www/banner_160x600.php' not found or unable to stat, referer: ://www.beautifulstarrysky.com/index.php?option=com_mailto&tmpl=component&link=b9131f144a565bd8b091fd4d5699cfe18c2b60eb
[Fri Jan 31 02:39:54.967606 2014] [:error] [pid 2543] [client 23.19.50.19:2465] script '/var/www/header53621.php' not found or unable to stat
[Fri Jan 31 02:39:54.986088 2014] [:error] [pid 2481] [client 192.151.152.245:3851] script '/var/www/ads.php' not found or unable to stat, referer: http://www.fashionwomenclothes.com/index.php?option=com_content&view=article&id=4772:2013-10-26-01-03-30&catid=20:clothes-shops&Itemid=103
...
Was it helpful?

Solution

Try something like below

#!/bin/bash
while read -r line; do
  [[ $line =~ 'client '([^:]+) ]] && iptables -I INPUT -s "${BASH_REMATCH[1]}" -j DROP
done < error.log

This will match everything between "client " and a colon as the ip (see @John1024's comment about doing it this way then just matching to colon), using BASH_REMATCH)

   BASH_REMATCH
          An  array  variable  whose members are assigned by the =~ binary
          operator to the [[ conditional command.  The element with  index
          0  is  the  portion  of  the  string matching the entire regular
          expression.  The element with index n  is  the  portion  of  the
          string matching the nth parenthesized subexpression.  This vari‐
          able is read-only.

OTHER TIPS

Using awk

awk '/error/{split($10,a,":");printf "iptables -I INPUT -s %s -j DROP\n", a[1]}' file |sh

Run the awk command without |sh first to confirm the output is correct, then add |sh to block the IPs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top