Skip to content

Instantly share code, notes, and snippets.

@jyxjjj
Created March 22, 2023 08:13
Show Gist options
  • Save jyxjjj/36c8ad838e7617e265d7d3cffca0c536 to your computer and use it in GitHub Desktop.
Save jyxjjj/36c8ad838e7617e265d7d3cffca0c536 to your computer and use it in GitHub Desktop.
Run smartctl then output the data to http
const http = require('node:http');
const fs = require('node:fs');
const cp = require('node:child_process');
const url = require('node:url');
const allowedDevices = /(sd[a-z]|nvme\d|nvme\dn1|disk\d)/;
const server = http.createServer();
server.on('request', getSmart);
server.listen(7627, '127.0.0.1');
function getSmart(req, res) {
try {
let deviceName = url.parse(req.url, true)?.query?.device || 'sda';
if (!allowedDevices.test(deviceName)) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Invalid device name');
return;
}
try {
let file = fs.statSync('/dev/' + deviceName);
} catch (e) {
if (e.code == 'ENOENT') {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Device not found');
return;
} else {
throw e;
}
}
let smartctl = cp.spawnSync('smartctl', ['-A', '/dev/' + deviceName]);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(smartctl.stdout);
} catch (e) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end("Internal server error");
console.error(e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment