Neemobeer

Cloud Security Engineer
Staff member
Joined
Jul 4, 2015
Messages
8,996
Another powershell script. This one is for monitoring systems and to send alerts if a monitored system is no longer pingable. It generates a balloon notification and an email alert. It is similar to my laptop tracking script. Run the script once to configure it then add your hosts you wish to monitor to the hosts file in the configuration folder one host per line.

Code:
$rootdir = "$env:ProgramData\Neemobeer"
$configdir = "$rootdir\ServerMonitor"
$credfile = "$configdir\cred"
$configfile = "$configdir\config"
$hostfile = "$configdir\hosts"


Function Set-Setup
{
    #Prompt for configuration information
    New-Item -Path $configdir -ItemType Directory
    "Configuration folder missing, please enter setup info..."
    $server = Read-Host -Prompt "Enter email server"
    $port = Read-Host -Prompt "Enter email port"
    $emailto = Read-Host -Prompt "Enter To email address"
    $emailfrom = Read-Host -Prompt "Enter From email address"
    $user = Read-Host -Prompt "Enter email username"
    Write-Host 'Enter your password:' -ForegroundColor Red
    $pass = Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File $credfile

        #Create Configuration File
    $monitor_file = New-Item -Path $configfile -ItemType File
    Out-File -FilePath $monitor_file.FullName -Append -InputObject ("server:$server")
    Out-File -FilePath $monitor_file.FullName -Append -InputObject ("port:$port")
    Out-File -FilePath $monitor_file.FullName -Append -InputObject ("username:$user")
    Out-File -FilePath $monitor_file.FullName -Append -InputObject ("to:$emailto")
    Out-File -FilePath $monitor_file.FullName -Append -InputObject ("from:$emailfrom")

    #Create hosts file
    New-Item -Path $hostfile -ItemType File
}

#Show a Notification balloon when a host is unreachable
Function Get-Notification([string]$Title, [string]$Message)
{

    $notify = New-Object System.Windows.Forms.NotifyIcon

    $notify.Icon = "C:\Windows\ProgressError.ico"
    $notify.BalloonTipIcon = "Error"
    $notify.BalloonTipText = $Message
    $notify.BalloonTipTitle = $Title

    $notify.Visible = $True
    $notify.ShowBalloonTip(5000)
}

#Setup configuration
If (!(Test-Path -Path $rootdir))
{
    New-Item -Path $rootdir -ItemType Directory
    Set-Setup
} ElseIf (!(Test-Path $configdir))
{
    New-Item -Path $configdir -ItemType Directory
    Set-Setup
}
Else
{
    $server =""
    $port = ""
    $to = ""
    $from = ""
    $user = ""

    #Read configuration file to configure
    #sending email
    $config = Get-Content $configfile
    Foreach ($c In $config)
    {
        If($c.Contains("server:"))
        {
            $split = $c.Split(":")
            $server = $split[1]
        }
        If($c.Contains("port:"))
        {
            $split = $c.Split(":")
            $port = $split[1]
        }
        If($c.Contains("from:"))
        {
            $split = $c.Split(":")
            $from = $split[1]
        }
        If($c.Contains("to:"))
        {
            $split = $c.Split(":")
            $to = $split[1]
        }
        If($c.Contains("username:"))
        {
            $split = $c.Split(":")
            $user = $split[1]
        }
    }

    #Create Credential object for sending email
    $secpass = Get-Content $credfile | ConvertTo-SecureString
    $PSCred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user,$secpass


    $hosts = (Get-Content $hostfile)

    While ($True)
    {
        "Checking hosts at $(Get-Date)"
        ForEach ($h In $hosts)
        {
            If (!(Test-Connection -ComputerName $h -Quiet))
            {
                Get-Notification -Title "Host Down" -Message "Host: $h is down"
                #Form html message body
                $header = "<!DOCTYPE html>`r<html>`r<head>`r<meta charset=`"UTF-8`"></head>"
                $body += $header
                $body = "<body>`r<p>Host: $h appears to be down."
                              
                #send email
                Send-MailMessage -SmtpServer $server -Port:$port -From $from -To $to `
                    -Subject "External IP has changed" -BodyAsHtml $body -Credential $PSCred -UseSsl
            } Else
            {
                "Host: $h is up"
            }
        }
        "Sleeping at $(Get-Date)"
        Start-Sleep -Seconds 360
    }
}
 


Last edited:
Solution
The PowerShell script you provided serves as a simple server monitoring tool that checks if specified hosts are reachable and sends email alerts if they are offline. Here's a breakdown of the script's core functionalities: 1. Setup Check: The script checks for the presence of the required configuration files and sets up the initial configuration if not found. 2. Notification: The Get-Notification function is responsible for displaying a balloon notification on the system tray when a monitored host is unreachable. 3. Email Sending: The script uses the Send-MailMessage cmdlet to send an email notification when a host is offline. 4. Host Monitoring Loop: The main logic monitors the specified hosts by...
The PowerShell script you provided serves as a simple server monitoring tool that checks if specified hosts are reachable and sends email alerts if they are offline. Here's a breakdown of the script's core functionalities: 1. Setup Check: The script checks for the presence of the required configuration files and sets up the initial configuration if not found. 2. Notification: The Get-Notification function is responsible for displaying a balloon notification on the system tray when a monitored host is unreachable. 3. Email Sending: The script uses the Send-MailMessage cmdlet to send an email notification when a host is offline. 4. Host Monitoring Loop: The main logic monitors the specified hosts by attempting to ping them. If a host is unreachable, a notification is displayed, and an email alert is sent. 5. Continuous Monitoring: The script loops indefinitely, periodically checking the hosts at defined intervals. This script can be a useful tool for monitoring critical hosts and receiving timely alerts. It's structured to be efficient and lightweight and can be expanded further based on specific monitoring needs. If you encounter any issues while running the script or need to customize it further, feel free to ask for assistance!
 


Solution
Back
Top