How to Get Your System’s Geographic Location From a Bash Script

Share
  • February 22, 2019

Toria/Shutterstock.com

You can find the geographic location of a remote Linux system using open APIs and a simple bash script. Geolocating a server could help you track it in the physical world, ensuring servers are located in regional hotspots.

Each server on the internet has a public-facing IP address. This is either directly assigned to the server, or assigned to a router that sends traffic to that server. IP addresses give us a clue about where that server is located in the world. We can get this geolocation data through two open APIs, provided by ipinfo.co and IP Vigilante and use it to see the city, state, and country associated with a server or other remote system. This doesn’t give you a precise GPS location; it just lets you see the general area of the IP address.

Connect to a Remote System

You’ll be running the following commands on the Linux server or other remote systems you want to geolocate, so you must connect to the server and access a shell on it first. For example, you might connect via SSH. You could run the commands on your local system to find its location, but you probably already know where you are!

Install curl and jq

We need two tools to access the geolocation API: curl to make HTTP requests and  jq to process the JSON data that we get back. Open a terminal and use  apt-get to install these tools on Ubuntu or Debian-based systems. On other Linux distributions, use your Linux distribution’s package installation tool instead.

sudo apt-get install curl jq

Find the Server’s Public IP Address

We also need the server’s public IP address before we can get the geolocation data. Use curl to make an API call to ipinfo.io in your terminal window.

curl https://ipinfo.io/ip

Get Location Data From The API

Now that we have the public IP of the server, we can make a call to ipvigilante.com’s API to get the geolocation data. Replace with the address that came back in the previous command.

curl https://ipvigilante.com/

output from curl command

Let’s take a closer look at what data we get back from this call:

metadata showing location information

Read the remaining 9 paragraphs

Source : How to Get Your System’s Geographic Location From a Bash Script