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
| const { exec } = require('child_process'); const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({ host: 'smtp.qq.com', port: 465, secure: true, auth: { user: 'your_email@qq.com', pass: 'your_auth_code' } });
async function sendAlert(serviceName) { await transporter.sendMail({ from: 'your_email@qq.com', to: 'admin@example.com', subject: '服务器服务异常告警', text: `服务 ${serviceName} 异常,时间:${new Date().toLocaleString()}` }); }
function checkService(command, serviceName) { return new Promise((resolve) => { exec(command, (error, stdout) => { const count = parseInt(stdout.trim()) || 0; resolve({ name: serviceName, running: count > 0, count }); }); }); }
async function monitorServices() { const services = [ { cmd: "ps -ef|grep node|grep -v grep|wc -l", name: 'Node.js' }, { cmd: "netstat -lntup|grep mongod|wc -l", name: 'MongoDB' }, { cmd: "netstat -lntup|grep nginx|wc -l", name: 'Nginx' } ];
const results = await Promise.all( services.map(s => checkService(s.cmd, s.name)) );
for (const result of results) { if (!result.running) { console.log(`${result.name} 服务异常,准备重启...`); await sendAlert(result.name); await restartService(result.name); } } }
async function restartService(serviceName) { const commands = { 'Node.js': 'cd /data/nodejs/ && sudo sh api.sh', 'MongoDB': 'sudo systemctl restart mongod', 'Nginx': 'sudo systemctl restart nginx' };
if (commands[serviceName]) { exec(commands[serviceName], (error) => { if (error) { console.error(`${serviceName} 重启失败:`, error); } else { console.log(`${serviceName} 重启成功`); } }); } }
setInterval(monitorServices, 60000); monitorServices();
|