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

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


Solution 1:[1]

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.

Solution 2:[2]

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:]_])/.

Solution 3:[3]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kuroikenshi
Solution 2 dan
Solution 3