-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnginx_mail.bat
More file actions
84 lines (72 loc) · 2.74 KB
/
Copy pathnginx_mail.bat
File metadata and controls
84 lines (72 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
@echo off
setlocal
:: ========== CONFIG ==========
rem
set "NGINX_PATH=%~dp0"
rem
if "%NGINX_PATH:~-1%"=="\" set "NGINX_PATH=%NGINX_PATH:~0,-1%"
set LOG_FILE=%NGINX_PATH%\monitor_nginx.log
set STATUS_FILE=%NGINX_PATH%\nginx_status.tmp
set URL=http://localhost:80/
:: Email Settings
set EMAIL_FROM=xxxxxxxxxx@gmail.com
set EMAIL_TO=xxxxxxxxx@gmail.com
set EMAIL_USER=xxxxxxxxxx@gmail.com
set "EMAIL_PASS=xxxxxxxxxxxx"
:: ============================
set "LAST_STATUS=unknown"
if exist "%STATUS_FILE%" (
set /p LAST_STATUS=<"%STATUS_FILE%"
)
:loop
tasklist | findstr /i nginx.exe >nul
if errorlevel 1 (
set "CURRENT_STATUS=stopped"
) else (
:: ตรวจสอบว่าเว็บตอบ status 200 หรือไม่
for /f %%a in ('powershell -Command "try { $r = Invoke-WebRequest -Uri '%URL%' -UseBasicParsing -TimeoutSec 5; if ($r.StatusCode -eq 200) {Write-Output 200} else {Write-Output $r.StatusCode} } catch { Write-Output 'error' }"') do set "HTTP_CODE=%%a"
if "%HTTP_CODE%"=="200" (
set "CURRENT_STATUS=running"
) else (
set "CURRENT_STATUS=unresponsive"
)
)
set "CURRENT_TIME=[%date% %time%]"
if not "%CURRENT_STATUS%"=="%LAST_STATUS%" (
echo %CURRENT_TIME% Nginx status : %CURRENT_STATUS% >> %LOG_FILE%
echo %CURRENT_STATUS% > "%STATUS_FILE%"
if "%CURRENT_STATUS%"=="stopped" (
echo %CURRENT_TIME% restarting Nginx... >> %LOG_FILE%
call :sendEmail "🚨 NGINX หยุดทำงาน! กำลังรีสตาร์ท..."
cd /d %NGINX_PATH%
start nginx
) else if "%CURRENT_STATUS%"=="unresponsive" (
echo %CURRENT_TIME% Nginx process running but HTTP not 200 >> %LOG_FILE%
echo %CURRENT_TIME% Attempting to restart Nginx...
call :sendEmail "⚠️ NGINX ไม่ตอบสนอง! รีสตาร์ท nginx ใหม่..."
cd /d %NGINX_PATH%
taskkill /F /IM nginx.exe >nul 2>&1
start nginx
) else (
echo %CURRENT_TIME% Nginx is running and responsive.
)
set LAST_STATUS=%CURRENT_STATUS%
) else (
echo %CURRENT_TIME% Nginx status: %CURRENT_STATUS% nochange
)
timeout /t 10 >nul
goto loop
:: ========= Function: sendEmail =========
:sendEmail
set MSG=%~1
powershell -Command ^
"$smtpServer = 'smtp.gmail.com';" ^
"$smtpFrom = '%EMAIL_FROM%';" ^
"$smtpTo = '%EMAIL_TO%';" ^
"$subject = 'แจ้งเตือนจาก NGINX Server (%COMPUTERNAME%)';" ^
"$body = '%MSG% เวลา: ' + (Get-Date).ToString();" ^
"$user = '%EMAIL_USER%';" ^
"$pass = ConvertTo-SecureString '%EMAIL_PASS%' -AsPlainText -Force;" ^
"$cred = New-Object System.Management.Automation.PSCredential($user, $pass);" ^
"Send-MailMessage -From $smtpFrom -To $smtpTo -Subject $subject -Body $body -SmtpServer $smtpServer -Port 587 -UseSsl -Credential $cred"
goto :eof