Office 365 IP address Range Monitor

Many of us working with office 365 administration has to keep an eye on any changes in IP address ranges that Microsoft does from time to time.

I have built this script keeping that in mind and is already been used by some of our customers especially admins who are responsible for Exchange online can use it without making any changes to it.

It is using rest based webservice that Microsoft has released so that solution like these can be built ūüôā

https://docs.microsoft.com/en-us/office365/enterprise/urls-and-ip-address-ranges

Download the Solution from below link and schedule it from task scheduler.

https://gallery.technet.microsoft.com/scriptcenter/Office-365-IP-address-52887199

If logs, report and Temp folder does not exists, script will create it automatically on first run.

Logs: for transcript log

Report: for capturing the IP range and what changed.

Temp: for keeping the previous run file to compare with new file.

Update the ps1 file –>¬†Variable and logs Section

$smtpserver

$email1

$erroremail

$from

$serviceArea1  #change it only, if you want to monitor other than Exchnage online.

 #########################Variable and logs###############

$log¬†=¬†Write-Log¬†-Name¬†“process_OnlineIpRange”¬†-folder logs -Ext log
$CurrentReport¬†=¬†Write-Log¬†-Name¬†“CurrentEOlReport”¬†-folder Report -Ext csv
$ChangeReport¬†=¬†Write-Log¬†-Name¬†“ChangeEOlReport”¬†-folder Report -Ext csv
$staticReport¬†= (Get-Location).Path +¬†“\temp\staticreport.csv”

 

$SmtpServer¬†=¬†“smtpservder”
$email1¬†=¬†“VSukhija@labtest.com”
$erroremail¬†=¬†“ReportsLogs@labtest.com”
$From¬†=¬†“DoNotReply@Labstest.com”

 

$serviceArea1¬†=¬†“Exchange”
$collection = @()
###start fetching the Ip addreses from endpoint to CSV Report###########

 

Ones the script is scheduled to run daily, if there is any change (Addition/ Removal) of IP address by Microsoft you will get email alert with report on what changed.

 

Now you can just send this to your security team to update in firewall (some times it would be Addition of New IP range and some times removal of obsolete range)

 

Task Scheduler Settings that you should not forget is Start in (optional): should be populated with the directory from which script is running.

 


 
Note: Logs and Reporting recycling is set to 60 days which you can change as per your requirement.

 

<#     
    .NOTES 
    =========================================================================== 
    Created with:     ISE 
    Created on:       10/23/2018  
    Created by:       Vikas Sukhija (http://SysCloudPro.com) 
    Organization:      
    Filename:         ExchangeOnlineIpRange.ps1 
    =========================================================================== 
    .DESCRIPTION 
    Office 365 IP range Monitor 
#> 
function Write-Log 
{ 
  [CmdletBinding()] 
  param 
  ( 
    [Parameter(Mandatory = $true,ParameterSetName = 'Create')] 
    [array]$Name, 
    [Parameter(Mandatory = $true,ParameterSetName = 'Create')] 
    [string]$Ext, 
    [Parameter(Mandatory = $true,ParameterSetName = 'Create')] 
    [string]$folder, 
     
    [Parameter(ParameterSetName = 'Create',Position = 0)][switch]$Create, 
     
    [Parameter(Mandatory = $true,ParameterSetName = 'Message')] 
    [String]$Message, 
    [Parameter(Mandatory = $true,ParameterSetName = 'Message')] 
    [String]$path, 
    [Parameter(Mandatory = $false,ParameterSetName = 'Message')] 
    [ValidateSet('Information','Warning','Error')] 
    [string]$Severity = 'Information', 
     
    [Parameter(ParameterSetName = 'Message',Position = 0)][Switch]$MSG 
  ) 
  switch ($PsCmdlet.ParameterSetName) { 
    "Create" 
    { 
      $log = @() 
      $date1 = Get-Date -Format d 
      $date1 = $date1.ToString().Replace("/", "-") 
      $time = Get-Date -Format t 
     
      $time = $time.ToString().Replace(":", "-") 
      $time = $time.ToString().Replace(" ", "") 
     
      foreach ($n in $Name) 
      {$log += (Get-Location).Path + "\" + $folder + "\" + $n + "_" + $date1 + "_" + $time + "_.$Ext"} 
      return $log 
    } 
    "Message" 
    { 
      $date = Get-Date 
      $concatmessage = "|$date" + "|   |" + $Message +"|  |" + "$Severity|" 
      switch($Severity){ 
        "Information" 
        {Write-Host -Object $concatmessage -ForegroundColor Green} 
        "Warning" 
        {Write-Host -Object $concatmessage -ForegroundColor Yellow} 
        "Error" 
        {Write-Host -Object $concatmessage -ForegroundColor Red} 
      } 
       
      Add-Content -Path $path -Value $concatmessage 
    } 
  } 
} 
function ProgressBar 
{ 
  [CmdletBinding()] 
  param 
  ( 
    [Parameter(Mandatory = $true)] 
    $Title, 
    [Parameter(Mandatory = $true)] 
    [int]$Timer 
  ) 
     
  For ($i = 1; $i -le $Timer; $i++) 
  { 
    Start-Sleep -Seconds 1; 
    Write-Progress -Activity $Title -Status "$i" -PercentComplete ($i /10 * 100) 
  } 
} 
#################Check if logs folder is created################## 
$logpath  = (Get-Location).path + "\logs" 
$reportpath  = (Get-Location).path + "\report"  
$temppath  = (Get-Location).path + "\temp"  
$testlogpath1 = Test-Path -Path $logpath 
$testlogpath2 = Test-Path -Path $reportpath 
$testlogpath3 = Test-Path -Path $temppath 
if($testlogpath1 -eq $false) 
{ 
  ProgressBar -Title "Creating logs folder" -Timer 10 
  New-Item -Path (Get-Location).path -Name Logs -Type directory 
} 
if($testlogpath2 -eq $false) 
{ 
  ProgressBar -Title "Creating Report folder" -Timer 10 
  New-Item -Path (Get-Location).path -Name Report -Type directory 
} 
 
if($testlogpath3 -eq $false) 
{ 
  ProgressBar -Title "Creating Temp folder" -Timer 10 
  New-Item -Path (Get-Location).path -Name Temp -Type directory 
} 
#########################Variable and logs############### 
$log = Write-Log -Name "process_OnlineIpRange" -folder logs -Ext log 
$CurrentReport = Write-Log -Name "CurrentEOlReport" -folder Report -Ext csv 
$ChangeReport = Write-Log -Name "ChangeEOlReport" -folder Report -Ext csv 
$staticReport = (Get-Location).Path + "\temp\staticreport.csv" 
 
$SmtpServer = "smtpserver" 
$email1 = "VSukhija@labtest.com" 
$erroremail = "ReportsLogs@labtest.com" 
$From = "DoNotReply@labtest.com" 
 
$endpoint = "https://endpoints.office.com/endpoints/worldwide?clientrequestid=b10c5ed1-bad1-445f-b386-b919946339a7" 
$serviceArea1 = "Exchange" 
$collection = @() 
#####################start fetching the Ip addreses from endpoint to CSV Report############## 
Start-Transcript -Path $log 
Get-Date 
$testpath = Test-Path -Path $staticReport 
 
if($testpath -eq $false){ 
  try{ 
    $getallonlineips = Invoke-RestMethod -Uri $endpoint 
    $geteolips = $getallonlineips | Where-Object -FilterScript {$_.servicearea -eq $serviceArea1} 
 
    $geteolips | ForEach-Object -Process { 
      $ips = $_.ips 
      $ips | ForEach-Object -Process { 
        $mcoll = "" | Select-Object -Property IPS 
        $mcoll.ips = $_ 
        $collection += $mcoll 
      } 
    } 
 
    $collection | 
    Sort-Object | 
    Select-Object -Property IPS -Unique | 
    Export-Csv $staticReport -NoTypeInformation 
    Copy-Item $staticReport $CurrentReport 
  } 
  catch{ 
    $_.Exception 
    Write-Host -Object "exception has occured EOL IP ranges" -ForegroundColor Yellow 
    Send-MailMessage -SmtpServer $SmtpServer -From $From -To $erroremail -Subject "Error occured EOL IP ranges " -Body $($_.Exception.Message) 
    break 
  } 
} 
else{ 
  try{ 
    $getallonlineips = Invoke-RestMethod -Uri $endpoint 
    $geteolips = $getallonlineips | Where-Object -FilterScript {$_.servicearea -eq $serviceArea1} 
 
    $geteolips | ForEach-Object -Process { 
      $ips = $_.ips 
      $ips | ForEach-Object -Process { 
        $mcoll = "" | Select-Object -Property IPS 
        $mcoll.ips = $_ 
        $collection += $mcoll 
      } 
    } 
 
    $collection | 
    Sort-Object | 
    Select-Object -Property IPS -Unique | 
    Export-Csv $CurrentReport -NoTypeInformation 
  } 
  catch{ 
    $_.Exception 
    Write-Host -Object "exception has occured EOL IP ranges" -ForegroundColor Yellow 
    Send-MailMessage -SmtpServer $SmtpServer -From $From -To $erroremail -Subject "Error occured EOL IP ranges " -Body $($_.Exception.Message) 
    break 
  } 
} 
###############################Compare and send report################################# 
 
try{ 
  $Changes = Compare-Object -ReferenceObject $(Import-Csv $CurrentReport) -DifferenceObject $(Import-Csv $staticReport) -Property IPS |  
  Select-Object -Property IPS, @{ 
    n = 'State' 
    e = {If ($_.SideIndicator -eq "=>"){"Removal" } Else { "Addition" }} 
  } 
   
  if($Changes){$Changes | Export-Csv $ChangeReport -NoTypeInformation 
    Send-MailMessage -SmtpServer $SmtpServer -From $From -To $erroremail, $email1 -Subject "EOL IP range Change Report" -Body "EOL IP range Change Report" -Attachments $ChangeReport 
  } 
} 
catch{Write-Host -Object "exception has occured EOL IP ranges Comparison" -ForegroundColor Yellow 
  Send-MailMessage -SmtpServer $SmtpServer -From $From -To $erroremail -Subject "Error occured EOL IP ranges Comparison" -Body $($_.Exception.Message) 
  break 
} 
 
Copy-Item $CurrentReport $staticReport -Force # update static report 
################################Recycle logs and report################## 
 
$path1 = (Get-Location).path + "\report\" 
$path2 = (Get-Location).path + "\Logs\" 
$limit = (Get-Date).AddDays(-60) #for report recycling 
Get-ChildItem -Path $path1 | 
Where-Object -FilterScript {$_.CreationTime -lt $limit} | 
Remove-Item -Recurse -Force 
     
Get-ChildItem -Path $path2 | 
Where-Object -FilterScript {$_.CreationTime -lt $limit} | 
Remove-Item -Recurse -Force 
     
Get-Date 
Write-Host -Object "Script finished" -ForegroundColor green 
Stop-Transcript 
Send-MailMessage -SmtpServer $SmtpServer -From $From -To $erroremail -Subject "Transcript Log - EOL IP Range Comparison" -Body "Transcript Log - EOL IP Range Comparison" -Attachments $log 
########################################################################################################
Thanks for downloading
Sukhija Vikas

 

Advertisements

One thought on “Office 365 IP address Range Monitor

  1. Pingback: Office 365 IP address Range Monitor | Cloud Computers Guide

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s