Monitor Website IP Changes Hourly with PowerShell and Capture Ping Results

 ## Monitor Website IP Changes Hourly with PowerShell and Capture Ping Results


This blog post will guide you through creating a PowerShell script that automatically checks if a specific website's IP address has changed every hour. If a change is detected, the script will execute the `ping` command and save a screenshot of the output to a designated folder.


Here's the PowerShell script:


```powershell

# Configuration

$TargetSite = "example.com"  # Website address to monitor for IP changes

$LogFilePath = "C:\Temp\IPChangeLog.txt" # Path to save the log file

$ScreenshotFolderPath = "C:\Screenshots" # Folder path to save screenshots


# Create the screenshot folder if it doesn't exist

if (-not (Test-Path -Path $ScreenshotFolderPath -PathType Container)) {

    New-Item -Path $ScreenshotFolderPath -ItemType Directory -Force | Out-Null

}


# Initialize variable to store the previous IP address

$PreviousIP = $null


# Function to check for IP change and capture screenshot

function Check-IPChange {

    param(

        [string]$Site

    )


    try {

        # Get the current IP address using Resolve-DnsName

        $CurrentIP = (Resolve-DnsName -Name $Site).IpAddress


        # Compare with the previous IP address

        if ($PreviousIP -ne $CurrentIP) {

            # IP address has changed

            $Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"

            Write-Host "$Timestamp - IP address changed: $PreviousIP -> $CurrentIP ($Site)"


            # Log the change to the file

            "$Timestamp - IP address changed: $PreviousIP -> $CurrentIP ($Site)" | Out-File -Append $LogFilePath


            # Execute the ping command

            $PingOutput = ping $Site

            Write-Host "Ping Result:"

            Write-Host $PingOutput


            # Save a screenshot

            $ScreenshotFileName = "<span class="math-inline">ScreenshotFolderPath\\$Site\-IPChanged\-</span>(Get-Date -Format "yyyyMMdd-HHmmss").png"

            Add-Type -AssemblyName System.Drawing

            Add-Type -AssemblyName System.Windows.Forms


            $bounds = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds

            $bitmap = New-Object System.Drawing.Bitmap($bounds.Width, $bounds.Height)

            $graphics = [System.Drawing.Graphics]::FromImage($bitmap)


            # Capture the entire screen

            $graphics.CopyFromScreen($bounds.X, $bounds.Y, 0, 0, $bounds.Size)

            $bitmap.Save($ScreenshotFileName, [System.Drawing.Imaging.ImageFormat]::Png)


            Write-Host "Ping result screenshot saved to: $ScreenshotFileName"


            # Update the previous IP address

            $PreviousIP = $CurrentIP

        } else {

            # IP address has not changed

            $Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"

            # Write-Host "$Timestamp - IP address unchanged ($Site)" # Uncomment if you want to log unchanged status

        }


        # Update the previous IP address on the first run or when no change occurs

        if ($PreviousIP -eq $null) {

            $PreviousIP = $CurrentIP

        }


    } catch {

        Write-Error "An error occurred: $($_.Exception.Message)"

        "$Timestamp - An error occurred: $($_.Exception.Message)" | Out-File -Append $LogFilePath

    }

}


# Scheduling (run every hour)

$Action = {

    Check-IPChange -Site $TargetSite

}


$Trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddHours(1) -RepetitionInterval (New-TimeSpan -Hours 1) -RepetitionDuration ([TimeSpan]::MaxValue)

$TaskName = "Check-$TargetSite-IPChange"

$TaskDescription = "Checks the IP address of $TargetSite hourly and captures ping results if it changes."

$TaskAction = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NoProfile -WindowStyle Hidden -File `"$PSCommandPath`""


# Remove existing task if it exists (optional)

if (Get-ScheduledTask -TaskName $TaskName) {

    Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false

}


Register-ScheduledTask -TaskName $TaskName -Action $TaskAction -Trigger $Trigger -Description $TaskDescription


Write-Host "Task to check '$TargetSite' IP address hourly has been registered in Task Scheduler."

Write-Host "Log file: $LogFilePath"

Write-Host "Screenshot folder: $ScreenshotFolderPath"


Explanation:

  1. Configuration:

    • $TargetSite: Replace "example.com" with the actual website address you want to monitor.
    • $LogFilePath: Specify the path where you want to save the log file that records IP address changes.
    • $ScreenshotFolderPath: Define the folder where screenshots will be saved. The script will create this folder if it doesn't exist.
  2. Create Screenshot Folder:

    • The if statement checks if the specified screenshot folder exists. If not, it creates the folder using New-Item.
  3. Initialize Previous IP:

    • $PreviousIP = $null: This variable will store the IP address from the previous check. It's initialized to null.
  4. Check-IPChange Function:

    • Takes the $Site (website address) as a parameter.
    • Error Handling: The try...catch block handles potential errors during IP resolution or pinging.
    • Get Current IP: $CurrentIP = (Resolve-DnsName -Name $Site).IpAddress uses the Resolve-DnsName cmdlet to get the current IP address of the target website. This is a more reliable way than parsing ping output.
    • Compare IPs: It compares the $CurrentIP with the $PreviousIP.
    • IP Change Detected:
      • A timestamped message indicating the IP change is displayed and logged to the $LogFilePath.
      • The ping $Site command is executed, and the output is displayed.
      • Screenshot Capture:
        • The necessary .NET Framework assemblies for screen capturing (System.Drawing and System.Windows.Forms) are loaded.
        • The bounds of the primary screen are retrieved.
        • A Bitmap object is created with the screen dimensions.
        • A Graphics object is created from the Bitmap.
        • $graphics.CopyFromScreen() captures the entire screen.
        • The captured image is saved as a PNG file in the $ScreenshotFolderPath with a filename containing the site name and timestamp.
      • $PreviousIP is updated to the $CurrentIP.
    • No IP Change:
      • A timestamped message indicating no IP change is displayed (commented out by default, you can uncomment it if needed).
    • Initial IP Update:
      • If $PreviousIP is null (on the first run), it's set to the $CurrentIP.
  5. Scheduling:

    • $Action: Defines the script block to be executed (calling the Check-IPChange function).
    • $Trigger: Creates a scheduled task trigger to run the task once, starting one hour from the current time, and repeating every hour indefinitely.
    • $TaskName: Sets the name of the scheduled task.
    • $TaskDescription: Provides a description for the scheduled task.
    • $TaskAction: Defines the action to be performed, which is running the PowerShell script in a hidden window.
    • Remove Existing Task (Optional): The if block checks if a task with the same name already exists and removes it. You can modify or remove this part if needed.
    • Register-ScheduledTask: Registers the new scheduled task with the defined trigger, action, name, and description.
    • Confirmation messages are displayed, showing the log file path and screenshot folder.

How to Use:

  1. Copy the script and save it as a .ps1 file (e.g., CheckIP.ps1).
  2. Modify the $TargetSite, $LogFilePath, and $ScreenshotFolderPath variables at the beginning of the script to match your requirements.
  3. Run PowerShell as an administrator and execute the script. This will register the scheduled task.
  4. The script will now run every hour. If the IP address of the target website changes, a screenshot of the ping command output will be saved in the specified folder, and the change will be logged in the log file.

Important Notes:

  • Running the script to register the scheduled task might require administrator privileges due to Task Scheduler modifications.
  • The scheduled task will run automatically in the background according to the defined schedule.
  • The Resolve-DnsName cmdlet is available on Windows 8 and later, and Windows Server 2012 and later. For older systems, you might need to use [System.Net.Dns]::GetHostAddresses($Site).IPAddressToString or parse the output of nslookup, although Resolve-DnsName is generally more reliable.
  • The script captures the entire primary screen. If you need to capture a specific window or region, you'll need to add more advanced screen capturing logic.
  • Ensure that the user account under which the scheduled task runs has the necessary permissions to write to the specified log file path and screenshot folder.

댓글

이 블로그의 인기 게시물

Troubleshooting VMware Horizon Client vdpConnect_Failure Issue

The Best AI Solutions for VMware Administrators

Troubleshooting Slow Initial Login with Group Policy in an AD Domain