batch script to send email notification once if any service goes down and sends mail once service is up

Hi Everyone,

Recently I came across an issue where oracle service on windows was getting stopped due to some reason. Since customer was not using any monitoring tool, it was very hard to track when the service was going down.

To mitigate the problem , I wrote a batch script which will monitor oracleservice and listener service on windows . The script will send a mail once notifying service has gone down and once service comes back it will send another notification on email with service is running message.

Save the following script in .bat format and schedule it as per your requirement in task scheduler.

@echo off

setlocal enabledelayedexpansion

set my_date=%date%

set my_time=%TIME%

set my_hours=%my_time:~0,2%

set my_minutes=%my_time:~3,2%

set my_seconds=%my_time:~6,2%

 

rem Configure email settings

 

set TO_EMAIL=soumya.das@email.com

set FROM_EMAIL=noreply@alerts.com

set SMTP_SERVER=smtp.gmail.com

set SMTP_PORT=587 

set SMTP_USER=noreply@alerts.com

set SMTP_PASSWORD=Password

set SUBJECT="Service Monitor Alert"

 

rem List of services to monitor (add more as needed)

set "SERVICES=OracleServiceORCL OracleOraDB19Home1TNSListener"

 

rem Create a temporary file to store service status

set STATUS_FILE=status.txt

 

rem Loop through the services and check their status using PowerShell

for %%s in (%SERVICES%) do (

    sc query "%%s" | find "STATE" | find "RUNNING" >nul

    if errorlevel 1 (

        echo %%s service is not running.

        if not exist !STATUS_FILE! (

            echo Sending email notification.

            powershell -command "Send-MailMessage -From '%FROM_EMAIL%' -To '%TO_EMAIL%' -Subject '%SUBJECT%' -Body 'The %%s service is not running.' -SmtpServer '%SMTP_SERVER%' -Port %SMTP_PORT% -UseSsl -Credential (New-Object PSCredential('%SMTP_USER%', (ConvertTo-SecureString '%SMTP_PASSWORD%' -AsPlainText -Force)))"

            rem Create the status file to indicate that an alert has been sent

            echo DOWN > !STATUS_FILE!

        )

    ) else (

        echo %%s service is running.

        if exist !STATUS_FILE! (

            echo Sending email notification.

            powershell -command "Send-MailMessage -From '%FROM_EMAIL%' -To '%TO_EMAIL%' -Subject 'Service Monitor Alert' -Body 'The %%s service is now running.' -SmtpServer '%SMTP_SERVER%' -Port %SMTP_PORT% -UseSsl -Credential (New-Object PSCredential('%SMTP_USER%', (ConvertTo-SecureString '%SMTP_PASSWORD%' -AsPlainText -Force)))"

            rem Delete the status file to indicate that the service is running

            del !STATUS_FILE!

        )

    )

)

 

endlocal