Website change alerts with powershell
Had a requirement to monitor a website for changes. Used free online tool www.changedetection.com. But set up a second monitoring tool using PowerShell and a scheduling system. Remix the following code in your own monitoring projects. Maybe turn it into a function. Maybe test for an expected string (eg the HTML for login form). There’s no defensive code to recover if the website is inaccessible (needs a try-catch there). Could add some code to raise a SNMP trap, or create a support ticket. Currently just sends emails alerts. Note it does web proxy authentication.
$url="http://blog.alexmags.com"
$folder=$env:temp
$oldfilepath="$folder\\webdiffold.html"
$Newfilepath="$folder\\webdiffNew.html"
$Diffsfilepath="$folder\\webdiffs.txt"
$emailTo="[put an email distribution group here](mailto:websitechanges-mon@companyname.com)"
$emailFrom="put an email address here permitted to send emails"
$emailServer="My SMTP server FQDN"
$emailSubject="Website $url has changed"
$emailbody="This is an automated email.\`nWebsite $url has changed. Current website HTML and previous are attached"
$webClient = new-object System.Net.WebClient
$webClient.Headers.Add("user-agent", "PowerShell Script") # Or you can imitate IE/Chrome
$webClient.Proxy.Credentials = \[System.Net.CredentialCache\]::DefaultNetworkCredentials
``````
$html = $webClient.DownloadString($url)
$html | set-content -path $newfilePath
``````
if (test-path $oldfilepath) {
# file exists. Do a compare
$oldhtml=Get-Content $oldfilepath
$newhtml=Get-Content $newfilepath
if (Compare-Object $oldhtml $newhtml) {
# not the same - fire alert!
Compare-Object $oldhtml $newhtml > $Diffsfilepath
write-host "OMG. Something changed"
Send-MailMessage -To $emailTo -subject $emailSubject -body "$emailBody $diffs" -Attachments $oldfilepath,$newfilepath,$Diffsfilepath -SmtpServer $emailServer -from $emailFrom
}
else
{
write-host "Same old same old"
}
``````
}
``````
write-host "Saving HTML to $oldfilePath"
$html | set-content -path $oldfilePath
Find more IT Infrastructure tips at blog.alexmags.com