02 December 2014

Check WAN IP address at icanhazip.com and mail the results

Since my ISP had planned maintenance last week, i couldn't access my boxes at home from the internet. My WAN IP address had changed. This happens once a year maybe but it's annoying enough to make something for it.

I found a great script from Leon van Efferen, but it didn't do exactly what i needed so i modified it a bit.

First off the check against whatismyip.com didn't work anymore, so i modified that to check against icanhazip.com.

Which by the way you can also do from Powershell directly:
(Invoke-WebRequest icanhazip.com).Content.Trim()
Then i wanted to receive an email everyday just to know it's still working and to be able to check my IP address always, not only if it changes.

This is what i came up with:
###########################################################################
#
# NAME:  CheckWANIP 
#
# COMMENT: Check the WAN IP Address based on ifconfig.me Automation page
#   and e-mail a message .
#
###########################################################################

#Set Target Domain
$TargetDomain = "domain.com" #Enter your FQDN that is linked to your WAN ip address

Function SendMail {
$EmailFrom = "IPCheck@domain.com" #Enter the e-mail address it should send the message from.
$EmailTo = "user@domain.com" #Enter the e-mail address it should send the message to.
$Subject = "External IP Address at icanhazip.com is $current_WAN_IP" #Enter your subject the e-mail message should contain.
$Body = "Compare the IP addresses from domain.com $DNS_WAN_IP and DNS records from ifconfig.me $Current_WAN_IP"  #Enter the message that the e-mail should contain.
$SMTPServer = "smtp.gmail.com" #Enter the FQDN of your SMTP server eg. smtp.gmail.com
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25) #Enter your SMTP Port eg. 587
$SMTPClient.EnableSsl = $false # Change to $false if you don't want to use SSL
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
}

# Do not change anything below this line.
$DNS_WAN_IP = [System.Net.Dns]::GetHostAddresses("$TargetDomain") | select-object IPAddressToString -expandproperty  IPAddressToString
Write-host "Resolved IP Address of $TargetDomain = $DNS_WAN_IP" 
$Current_WAN_IP = (Invoke-WebRequest icanhazip.com).Content.Trim()
Write-host "Current WAN IP Address = $Current_WAN_IP"
SendMail
Write-host "Sending email"
exit

Then you can schedule it as a daily task:
Powershell.exe "& 'C:\path to script\CheckWANIP.ps1'"

No comments:

Post a Comment