How do i redirect a list of IP addresses to a command line function?

Viewed 84

I want to see what countries are trying to access my VPS. I have installed a tool called "goiplookup", which was forked from another effort called "geoiplookup". If I type this at the command line:

goiplookup 8.8.8.8

It returns this:

US, United States

So I figured out how to get a list of IPs that are trying to access my server by using this:

sudo grep "disconnect" /var/log/auth.log | grep -v COMMAND | awk '{print $9}'

Which gives a long list of IPs like this:

1.1.1.1
2.2.2.2
3.3.3.3

I cannot figure out how to get this list of IPs to be processed by the "goiplookup" tool. I tried this:

sudo grep "disconnect" /var/log/auth.log | grep -v COMMAND | awk '{print $9}' | goiplookup

but that did not work. I also tried with no luck:

sudo grep "disconnect" /var/log/auth.log | grep -v COMMAND | awk '{print $9}' | xargs -0 goiplookup
4 Answers

Try this:

sudo grep "disconnect" /var/log/auth.log | grep -v COMMAND | awk '{print $9}' | sort | uniq | xargs -n 1 goiplookup
  • I added | sort | uniq to ensure each IP only appears once
  • and xargs -n 1 so that each found IP is processes by goiplookup

I would put it into a file and make a small utility to parse it:

sudo grep "disconnect" /var/log/auth.log | grep -v COMMAND | awk '{print $9}' | sort -u > ./file.txt

cat ./file.txt | while read -r line; do
      temp$(echo $line)

      goiplookup $temp
done

This will read through the file one line at a time and execute the goiplookup with each IP.

sudo grep disconnect /var/log/auth.log | awk '!/COMMAND/ && !seen[$0]++ {system("geoiplookup \""$9"\""}
  • Note that geoiplookup only allows one IP per invocation.

  • The whole thing can be done in awk, but using grep allows the rest to be run unprivileged.

  • Consider whether grep -w (match whole word) is appropriate, and in awk you can do a similar thing with !/(^|[^[:alnum:]_])COMMAND($|[^[:alnum:]_])/.

I just made a shell script, which works.

#!/bin/bash
readarray -t array < <(sudo grep "disconnect" /var/log/auth.log | grep -v COMMAND | awk '{print $9}'  | sort | uniq)
for ip in "${array[@]}"
do
   :
 country=$(/usr/local/bin/goiplookup -c $ip)
 echo "$ip $country"
done
Related