node向后端Linux发送一条指令:ls -lh /usr,指令的返回数据展示到process_get中
- express_linux.js
const express = require('express');
const app = express();
const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);
let result = '';
app.get('/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "index_linux.html" );
})
ls.stdout.on('data', (data) => {
result += (`stdout: ${data}`)
});
ls.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
app.get('/process_get', function (req, res) {
res.send(result);
})
var server = app.listen(8080, function () {
var host = server.address().address
var port = server.address().port
console.log(server.address())
console.log("应用实例,访问地址为 http://%s:%s", host, port)
})
- index_linux.html
这里输入命令也没用,传递参数还没写,只有Submit有用!
<html>
<body>
<form action="/process_get" method="GET">
请输入Linux命令:<input type="text">
<input type="submit" value="Submit">
</form>
</body>
</html>
运行node express_linux.js
点击Submit,跳转至相应页面
在Windows上的话,得这样干:
const ls = spawn('cmd.exe',['/c','1.bat']);
网友评论