├── .gitattributes ├── CheckStatus.ps1 ├── CheckStatusConfig.ps1 ├── MonitorhMailServerTelnet.ps1 └── CheckStatusFunctions.ps1 /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /CheckStatus.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | 3 | .SYNOPSIS 4 | Test Windows Services 5 | 6 | .DESCRIPTION 7 | Make sure Windows Services are running throughout the day 8 | 9 | .FUNCTIONALITY 10 | 1) Checks to see if service is running 11 | 2) If not running, attempts to start 12 | 3) If service doesn't start, then its run through a restart routine 13 | 4) Sends notification messages by email and SMS 14 | 15 | .NOTES 16 | Run every 5 minutes via task scheduler 17 | 18 | .EXAMPLE 19 | 20 | #> 21 | 22 | <# Include required files #> 23 | Try { 24 | .("$PSScriptRoot\CheckStatusConfig.ps1") 25 | .("$PSScriptRoot\CheckStatusFunctions.ps1") 26 | } 27 | Catch { 28 | Write-Output "$(Get-Date -f G) : ERROR : Unable to load supporting PowerShell Scripts : $query `n$($Error[0])" | Out-File "$PSScriptRoot\PSError.log" -Append 29 | } 30 | 31 | <# First, check if machine recently rebooted #> 32 | If (PastBootup) { 33 | 34 | <# Put array of services into foreach loop #> 35 | ForEach ($ServiceName in $ServiceToCheck) { 36 | 37 | <# Check if script should run during backup #> 38 | If ($AvoidBackup) { 39 | <# If not being called during backup period, then run it #> 40 | If (($StartTime.TimeOfDay -le (Get-Date).TimeOfDay) -and ($EndTime.TimeOfDay -ge (Get-Date).TimeOfDay)) { 41 | TestService $ServiceName 42 | } 43 | 44 | <# If script should run all the time, then just do it #> 45 | } Else { 46 | TestService $ServiceName 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /CheckStatusConfig.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | 3 | .SYNOPSIS 4 | Test Windows Services 5 | 6 | .DESCRIPTION 7 | Make sure Windows Services are running throughout the day 8 | 9 | .FUNCTIONALITY 10 | 1) Checks to see if service is running 11 | 2) If not running, attempts to start 12 | 3) If service doesn't start, then its run through a restart routine 13 | 4) Sends notification messages by email and SMS 14 | 15 | .NOTES 16 | Run every 5 minutes via task scheduler 17 | 18 | .EXAMPLE 19 | 20 | #> 21 | 22 | ### SCRIPT VARIABLES ### 23 | $AvoidBackup = $True # if true, script will not run during backup routine in case hMailServer is shut down during backup 24 | $StartTime = Get-Date '02:00' # run script start time - sometime after nightly backup ends 25 | $EndTime = Get-Date '23:45' # run script end time - sometime before nightly backup begins 26 | $AvoidRecentBoot = 10 # number of minutes after reboot that script will not run (give time for services to fully startup and run) 27 | $Timeout = 3 # number of minutes to try service shutdown or startup before giving up 28 | 29 | ### SERVICES TO CHECK ### 30 | $ServiceToCheck = @( # array of services to check - check spelling in windows services console 31 | 'filezilla-server' 32 | 'hMailServer' 33 | 'ClamD' 34 | 'mysql' 35 | 'spamassassin' 36 | 'Apache2.4' 37 | 'syncthing' 38 | ) 39 | 40 | # 'OpenVPNService' 41 | # 'SEVPNSERVER' 42 | 43 | ### EMAIL VARIABLES ### 44 | $FromAddress = 'notification.txt.alerts@gmail.com' 45 | $Recipient = '9173286699@tmomail.net' 46 | $Subject = 'Windows Service Fault' 47 | $EmailBody = 'C:\scripts\EmailBody.txt' 48 | $FileAttachment = 'C:\scripts\somefile.log' 49 | $HTML = $False 50 | $SMTPServer = 'smtp.gmail.com' 51 | $SMTPAuthUser = 'notification.txt.alerts@gmail.com' 52 | $SMTPAuthPass = 'Cs!ll@2010' 53 | $SMTPPort = 587 54 | $SSL = $True 55 | $UseEmail = $False 56 | 57 | ### SMS VARIABLES ### 58 | $SMSTo = 9173286699 59 | $UseSMS = $True -------------------------------------------------------------------------------- /MonitorhMailServerTelnet.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | 3 | .SYNOPSIS 4 | Test telnet on hMailServer 5 | 6 | .DESCRIPTION 7 | Uses telnet to ensure hMailServer properly functioning 8 | 9 | .FUNCTIONALITY 10 | 1) Telnets in to hMailServer and checks for 220 Banner 11 | 2) If banner found, exit 12 | 3) If banner not found then wait, check again, if still not found then restart hMailServer service 13 | 4) Sends notification messages by email and SMS 14 | 15 | .NOTES 16 | Run every 5 minutes via task scheduler 17 | 18 | .EXAMPLE 19 | 20 | #> 21 | 22 | <### SCRIPT VARIABLES ###> 23 | $Banner = 'wap.dynu.net' # hMailServer smtp banner 24 | $ServiceName = 'hMailServer' # name of hMailServer service (installation default is 'hMailServer') 25 | $StreamFile = "$PSScriptRoot\telnetout.txt" # location of test output (temporary file) 26 | $Timeout = 5 # number of minutes to try service shutdown or startup before giving up 27 | 28 | <# Include required files #> 29 | Try { 30 | .("$PSScriptRoot\CheckStatusConfig.ps1") 31 | .("$PSScriptRoot\CheckStatusFunctions.ps1") 32 | } 33 | Catch { 34 | Write-Output "$(Get-Date -f G) : ERROR : Unable to load supporting PowerShell Scripts : $query `n$($Error[0])" | Out-File "$PSScriptRoot\PSError.log" -Append 35 | } 36 | 37 | <### FUNCTIONS ###> 38 | 39 | Function CkTelnet { 40 | $Socket = New-Object System.Net.Sockets.TcpClient('localhost', 25) 41 | If ($Socket) 42 | { $Stream = $Socket.GetStream() 43 | $Writer = New-Object System.IO.StreamWriter($Stream) 44 | $Buffer = New-Object System.Byte[] 1024 45 | $Encoding = New-Object System.Text.AsciiEncoding 46 | ForEach ($Command in $Commands) 47 | { $Writer.WriteLine($Command) 48 | $Writer.Flush() 49 | } 50 | } 51 | Start-Sleep -seconds (2) 52 | $Result = "" 53 | While($Stream.DataAvailable) 54 | { $Read = $Stream.Read($Buffer, 0, 1024) 55 | $Result += ($Encoding.GetString($Buffer, 0, $Read)) | Out-File $StreamFile 56 | } 57 | } 58 | 59 | Function SecondTry { 60 | <# Send notification, then wait 60 seconds and try telnet again #> 61 | $NotifyMsg = "ATTENTION! hMailServer is NOT RESPONDING to telnet commands. Check status NOW." 62 | Notify $NotifyMsg 63 | Start-Sleep -seconds 60 64 | <# Test telnet connection, if success then exit, if failure then restart service #> 65 | CkTelnet 66 | If (Test-Path $StreamFile){ 67 | $TestResult = Get-Content $StreamFile | Out-String 68 | Remove-Item -Path $StreamFile 69 | If ($TestResult -match $Banner){Exit} 70 | Else {RestartRoutine "hMailServer"} 71 | } 72 | Else {RestartRoutine "hMailServer"} 73 | } 74 | 75 | Function TryTelnet { 76 | <# Test telnet connection, if success then exit, if failure then wait 1 minute and try again #> 77 | CkTelnet 78 | If (Test-Path $StreamFile){ 79 | $TestResult = Get-Content $StreamFile | Out-String 80 | Remove-Item -Path $StreamFile 81 | If ($TestResult -match $Banner){Exit} 82 | Else {SecondTry} 83 | } 84 | Else {SecondTry} 85 | } 86 | 87 | <### START SCRIPT ###> 88 | 89 | <# Check if script should run during backup #> 90 | If ($AvoidBackup){ 91 | <# If not being called during backup period, then run it #> 92 | If (($StartTime.TimeOfDay -le (Get-Date).TimeOfDay) -and ($EndTime.TimeOfDay -ge (Get-Date).TimeOfDay)) { 93 | TryTelnet 94 | } 95 | <# If script should run all the time, then just do it #> 96 | } Else { 97 | TryTelnet 98 | } -------------------------------------------------------------------------------- /CheckStatusFunctions.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | 3 | .SYNOPSIS 4 | Test Windows Services 5 | 6 | .DESCRIPTION 7 | Make sure Windows Services are running throughout the day 8 | 9 | .FUNCTIONALITY 10 | 1) Checks to see if service is running 11 | 2) If not running, attempts to start 12 | 3) If service doesn't start, then its run through a restart routine 13 | 4) Sends notification messages by email and SMS 14 | 15 | .NOTES 16 | Run every 5 minutes via task scheduler 17 | 18 | .EXAMPLE 19 | 20 | #> 21 | 22 | Function Debug ($DebugOutput) { 23 | Write-Output "$(Get-Date -f G) : $DebugOutput" | Out-File "$PSScriptRoot\$((Get-Date).ToString('yyyy-MM-dd'))-Debug.log" -Encoding ASCII -Append 24 | } 25 | 26 | Function Notify($Body) { 27 | If ($UseEmail){ 28 | Try { 29 | Email $Body 30 | } 31 | Catch { 32 | Debug "Email Error: $($Error[0])" 33 | } 34 | } 35 | If ($UseSMS){ 36 | Try { 37 | SMS $Body 38 | } 39 | Catch { 40 | Debug "SMS Error: $($Error[0])" 41 | } 42 | } 43 | } 44 | 45 | Function Email($Body) { 46 | If (Test-Path $FileAttachment){$Attachment = New-Object System.Net.Mail.Attachment $FileAttachment} 47 | $Message = New-Object System.Net.Mail.Mailmessage $FromAddress, $Recipient, $Subject, $Body 48 | $Message.IsBodyHTML = [System.Convert]::ToBoolean($HTML) 49 | If (Test-Path $FileAttachment){$Message.Attachments.Add($FileAttachment)} 50 | $SMTP = New-Object System.Net.Mail.SMTPClient $SMTPServer,$SMTPPort 51 | $SMTP.EnableSsl = [System.Convert]::ToBoolean($SSL) 52 | $SMTP.Credentials = New-Object System.Net.NetworkCredential($SMTPAuthUser, $SMTPAuthPass); 53 | $SMTP.Send($Message) 54 | } 55 | 56 | Function SMS($Msg) { 57 | & C:\scripts\Twilio\TwilioSend.ps1 -Num $SMSTo -Msg $Msg 58 | } 59 | 60 | Function PastBootup { 61 | $OKToProceed = $False 62 | $MinutesSinceBoot = [int](New-Timespan ([DateTime]::ParseExact((((Get-WmiObject -Class win32_operatingsystem).LastBootUpTime).Split(".")[0]), 'yyyyMMddHHmmss', $null))).TotalMinutes 63 | If ($MinutesSinceBoot -gt $AvoidRecentBoot) {$OKToProceed = $True} 64 | 65 | Return $OKToProceed 66 | } 67 | 68 | Function TestService($ServiceName) { 69 | If ((Get-Service $ServiceName).Status -ne 'Running'){ 70 | $NotifyMsg = "ATTENTION! $ServiceName found to be not running. Attempting restart." 71 | Notify $NotifyMsg 72 | Start-Service $ServiceName 73 | Start-Sleep -seconds 60 74 | 75 | <# If still not running, send through restart routine #> 76 | (Get-Service $ServiceName).Refresh() 77 | If ((Get-Service $ServiceName).Status -ne 'Running'){ 78 | RestartRoutine $ServiceName 79 | } Else { 80 | $NotifyMsg = "$ServiceName successfully restarted." 81 | Notify $NotifyMsg 82 | } 83 | } 84 | } 85 | 86 | Function RestartRoutine($ServiceName) { 87 | <# Send notification, then restart service #> 88 | $NotifyMsg = "ATTENTION! $ServiceName service is being RESTARTED due to a fault. Check status NOW!" 89 | Notify $NotifyMsg 90 | 91 | <# Shutdown Routine #> 92 | $BeginShutdown = Get-Date 93 | Do { 94 | Stop-Service $ServiceName 95 | Start-Sleep -Seconds 60 96 | (Get-Service $ServiceName).Refresh() 97 | $ServiceStatus = (Get-Service $ServiceName).Status 98 | } Until (((New-Timespan -Start $BeginShutdown -End (Get-Date)).Minutes -gt $Timeout) -or ($ServiceStatus -eq "Stopped")) 99 | 100 | If ($ServiceStatus -ne "Stopped"){ 101 | $NotifyMsg = "$ServiceName could not be stopped during restart process. Check status NOW." 102 | Notify $NotifyMsg 103 | Exit 104 | } 105 | 106 | <# Startup Routine #> 107 | $BeginStartup = Get-Date 108 | Do { 109 | Start-Service $ServiceName 110 | Start-Sleep -seconds 60 111 | (Get-Service $ServiceName).Refresh() 112 | $ServiceStatus = (Get-Service $ServiceName).Status 113 | } Until (((New-Timespan -Start $BeginStartup -End (Get-Date)).Minutes -gt $Timeout) -or ($ServiceStatus -eq "Running")) 114 | 115 | If ($ServiceStatus -ne "Running"){ 116 | $NotifyMsg = "$ServiceName could not be started during restart process. Check status NOW." 117 | Notify $NotifyMsg 118 | Exit 119 | } 120 | } --------------------------------------------------------------------------------