如果我在 Node js 中执行某个 shell 命令,输出将显示在控制台上。有没有办法可以将其保存在变量中,以便可以将其 POST 到 Sqlite 数据库。
const shell = require('shelljs');
shell.exec('arp -a');
在这种情况下,我想将特定 MAC/物理地址的 IP 地址存储到数据库中。如何做到这一点?
任何帮助将不胜感激。谢谢您
最佳答案
您需要获取传递给 exec
的命令的输出。为此,只需调用 stdout,如下所示:
const shell = require('shelljs');
const stdout = shell.exec('arp -a').stdout;
然后只需解析该输出即可获取您的 IP 地址:
const entries = stdout.split('\r\n');
// entries sample
[ '',
'Interface: 10.17.60.53 --- 0xd',
' Internet Address Physical Address Type',
' 10.11.10.52 6c-4b-90-1d-97-b8 dynamic ',
' 10.10.11.254 xx-yy-53-2e-98-44 dynamic ']
然后您可以通过更多操作来过滤您想要的地址。
编辑:
要获取 IP 地址,您可以这样做:
let ipAddr = null;
for (let i = 0; i < entries.length; i++) {
if (entries[i].indexOf('6c-4b-90-1d-97-b8') > -1) {
ipAddr = entries[i].match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/)[0];
break;
}
}
console.log(ipAddr); // '10.11.10.52'
关于javascript - 将 shell 命令的输出存储在 sqlite 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48297791/