Nagpur Cha SysAdmin is a blog about tips, tricks, free PowerShell scripts, free tools and easy solutions for various day to day and advance tasks of system administrators.

Search This Blog

Tuesday 5 July 2016

Finding Geographical information (location/country) of IPs Using PowerShell

Hello Friends, One day early in the morning our team has got an alert for one of the critical website of ours and after reviewing the logs we got to know that it was kind of DDOS on our site. During the investigation of this issue i had to perform a very time consuming task.

That is collecting all the source host IPs from IIS log for this website and get their geographical details. So after performing this task manually, i have created a PowerShell Script to reducing the amount of time taken by the task next time onward. Hope you will find it usefull.



1.       Add “geoip” function to your System`s PowerShell by running below code in PowerShell ISE
================================================================
Function geoip
{
#requires -Version 3
$source = [string]$args[0]
$infoService = "http://freegeoip.net/xml/$source"
 $geoip = Invoke-RestMethod -Method Get -URI $infoService
 $geoip.Response
}
==================================================================

2.       Now you can use this function to get geo data of any IP.  Use this function as below
==================================
geoip 207.x.x.x

Output.
 
==================================
3.       Suppose if you have list of IP addresses for which you need to find their geo locations then you can use this function as below.
==========================
#importing IPs which are stored in a csv file to a veriable (ex. $SRV)
$SRV = Import-Csv -Path C:\ScriptTest\Demo_Servers.csv

#Applying the geoip function in foreach loop this will ensure that the function will get geo deatils for each and every IP
#here $MHost is veriable for MHost coulmn of our CSV file

foreach ($MHost in $SRV)
       {
      
    #Here $MHost.MHost is a veriable for Cell data. (Cell is containing IP)
    geoip $MHost.MHost | select IP,CountryName,City,TimeZone,ZipCode | Export-Csv d:\ipgeodata.csv -Append

       }

==========================
In this above example I have first created a CSV file “Demo_Servers.csv” at location “C:\ScriptTest\” which contains the list of IP addresses as shown below.

 
And storing/exporting the data containing information about IP,CountryName,City,TimeZone,ZipCode to CSV file “d:\ipgeodata.csv” this will automatically get created and will have results as shown below.
 

Kindly Share your experience in comment section with my blog/post if it did help you !!

Stay Blessed!!  
Thank You!!

No comments:

Post a Comment

Comments system