Get city location from IP addresses inside a file
Using a while read
loop:
while read -r ip; do curl --fail "ipinfo.io/${ip}/city" || break; done<ip_list.txt
This will read through the ip_list.txt
file and set each line to the ip
loop variable, then curl it.
Based on Stéphane's suggestion I have added the --fail
flag to curl so it will fail silently upon a server error and the || break
so that it will break out of the loop. ipinfo.io allows 50k API requests a month for free accounts so depending on how many IPs you have and how often you plan to use this that may be an issue for you.
For geographic IP address(es) lookup, I usually prefer using MaxMind's geoIP database. It is faster, as it does not an Internet connection for each IP address, as it uses a local database, and does not have limits on the number of calls.
If in Debian, as a pre-requisite, install the packages:
sudo apt-get install geoip-bin geoip-database-extra
Then run the script:
while read -r ip; do geoiplookup $ip | awk -F, ' /City/ { print $5 } ' \
; done < ip_list.txt > cities.txt