要通過JavaScript日志監控Debian系統狀態,你可以使用Node.js的child_process
模塊來執行系統命令并獲取輸出。以下是一個簡單的示例,展示了如何使用JavaScript和Node.js監控Debian系統的CPU使用率、內存使用情況和磁盤空間。
首先,確保你已經安裝了Node.js。如果沒有,請訪問Node.js官方網站下載并安裝。
然后,創建一個名為system_monitor.js
的文件,并將以下代碼粘貼到其中:
const { exec } = require('child_process');
// 獲取CPU使用率
function getCpuUsage(callback) {
exec('top -bn1 | grep load | awk \'{printf("CPU Usage: %.2f%%\\n", $(NF-2))}\'', (error, stdout, stderr) => {
if (error) {
console.error(`Error getting CPU usage: ${error}`);
return;
}
callback(stdout);
});
}
// 獲取內存使用情況
function getMemoryUsage(callback) {
exec('free -m | grep Mem | awk \'{printf("Memory Usage: %.2f%%\\n", $(3)/$(2)*100)}\'', (error, stdout, stderr) => {
if (error) {
console.error(`Error getting memory usage: ${error}`);
return;
}
callback(stdout);
});
}
// 獲取磁盤空間
function getDiskSpace(callback) {
exec('df -h | grep / | awk \'{printf("Disk Space: %s/%s (%.2f%%)\\n", $3, $2, $5)}\'', (error, stdout, stderr) => {
if (error) {
console.error(`Error getting disk space: ${error}`);
return;
}
callback(stdout);
});
}
// 每隔一段時間(例如5秒)執行一次監控
setInterval(() => {
getCpuUsage((cpuUsage) => console.log(cpuUsage));
getMemoryUsage((memoryUsage) => console.log(memoryUsage));
getDiskSpace((diskSpace) => console.log(diskSpace));
}, 5000);
保存文件后,在終端中運行以下命令以啟動監控腳本:
node system_monitor.js
這將每隔5秒輸出一次系統的CPU使用率、內存使用情況和磁盤空間。你可以根據需要調整setInterval
中的時間間隔。
請注意,這個示例僅用于演示目的,實際生產環境中可能需要更復雜的監控和錯誤處理。另外,你可以考慮使用現有的開源監控工具,如Prometheus和Grafana,以獲得更強大和靈活的系統監控功能。