-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserverTable.js
77 lines (69 loc) · 2.51 KB
/
serverTable.js
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 { Client } = require('ssh2');
const fs = require('fs');
function executeCommand(server, command, callback) {
const conn = new Client();
conn.on('ready', () => {
conn.exec(command, (err, stream) => {
if (err) throw err;
let output = '';
stream.on('data', data => {
output += data.toString();
});
stream.on('close', () => {
conn.end();
callback(output.trim());
});
});
}).connect({
host: server.host,
username: server.creds.user,
privateKey: fs.readFileSync(server.creds.privateKey)
});
}
function fetchStats(server) {
return new Promise((resolve, reject) => {
executeCommand(server, 'free -m', memoryOutput => {
executeCommand(server, 'df -h', diskOutput => {
executeCommand(server, 'top -bn1 | grep "Cpu(s)"', cpuOutput => {
const memoryStats = memoryOutput.split(/\s+/);
const diskStats = diskOutput.split('\n')[1].split(/\s+/);
const cpuUsage = cpuOutput.match(/(\d+\.\d+)%? id/);
const cpuUsagePercentage = cpuUsage ? (100 - parseFloat(cpuUsage[1])).toFixed(2) + '%' : 'N/A';
const serverStats = {
memoryTotal: memoryStats[7],
memoryUsed: memoryStats[8],
memoryFree: memoryStats[9],
diskTotal: diskStats[1],
diskUsed: diskStats[2],
diskAvailable: diskStats[3],
cpuUsage: cpuUsagePercentage
};
resolve(serverStats);
});
});
});
});
}
async function generateStatsTable(serverDataFilePath) {
const servers = require(serverDataFilePath);
console.log('Server Statistics:');
for (const server of servers) {
const stats = await fetchStats(server);
console.log(`Statistics for ${server.server_name}:`);
console.table([stats]);
console.log('\n-----------------------------\n');
}
}
async function getStatsByIndex(serverDataFilePath, index) {
const servers = require(serverDataFilePath);
if (index < 0 || index >= servers.length) {
throw new Error('Invalid index');
}
const server = servers[index];
const stats = await fetchStats(server);
return stats;
}
module.exports = {
generateStatsTable,
getStatsByIndex
};