我正在使用几个awk脚本来读/写我的网络接口文件。为了将这些脚本集成到我的Node.js项目中,我正在使用child_process.exec函数执行它们。
问题是read脚本的行为似乎有所不同,具体取决于它是否使用exec运行。
以下是我在Node中运行脚本的代码:
import cp from "child_process";
import {normalize, join} from "path";
const local = (path) => normalize(join(__dirname, path));
const readScript = local("/network-scripts/read-interface.awk");
const writeScript = local("/network-scripts/write-interface.awk");
function exec(cmd, options) {
return new Promise((resolve, reject) => {
cp.exec(cmd, options, (error, stdout, stderr) => {
if(error) reject(error);
else resolve({stdout, stderr});
});
});
}
function read(interfacesPath, interfaceName) {
return exec(`awk -f ${readScript} ${normalize(interfacesPath)} device=${interfaceName}`).then((data) => {
console.log(data);
return data;
});
}
这是我正在测试的interfaces文件:
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
# The loopback network interface
auto lo
iface lo inet loopback
# The primary network interface
auto eth0 eth1 eth2 eth3
iface eth0 inet static
address 10.0.11.100
netmask 255.255.255.0
gateway 10.0.11.1
iface eth1 inet manual
up ifconfig $IFACE 0.0.0.0 up
down ifconfig $IFACE down
iface eth2 inet static
address 192.168.1.2
netmask 255.255.255.0
gateway 192.168.1.254
iface eth3 inet dhcp
这是我的测试:
import intf from "../server/interfaces";
const testInterfaces = `${__dirname}/../test-interfaces`;
describe("interfaces", () => {
it("should be able to read a dynamic interface", (done) => {
intf.read(testInterfaces, "eth3").then(() => done(), done);
});
});
当我运行此测试时,我将此错误视为输出:
Failed: { [Error: Command failed: /bin/sh -c awk -f /Users/james1/Projects/pump-dashboard/server/network-scripts/read-interface.awk /Users/james1/Projects/pump-dashboard/test-interfaces device=eth3
]
killed: false,
code: 1,
signal: null,
cmd: '/bin/sh -c awk -f /Users/james1/Projects/pump-dashboard/server/network-scripts/read-interface.awk /Users/james1/Projects/pump-dashboard/test-interfaces device=eth3' }
但是,如果我直接从该错误中复制命令:
awk -f /Users/james1/Projects/pump-dashboard/server/network-scripts/read-interface.awk /Users/james1/Projects/pump-dashboard/test-interfaces device=eth3
并在我的终端中运行它,它按预期输出“dhcp”。
此外,如果我将输入设备的read
函数作为静态接口“eth0”运行,则脚本按预期工作(即使使用exec)。
为什么在使用exec vs在终端中运行命令(使用zsh)时会收到不同的结果?我该怎么做才能解决这个问题?