从stdout读取

我正在使用ssh-exec npm,我想得到一个远程ssh命令的结果,parsing它,并将其存储到一个数组中。 这是被输送到标准输出,而我不知道如何把它变成一个variables。

function GetRemoteLinuxIp(hostAddress) { console.log(hostAddress); exec("ifconfig -a | tr -s ' ' | awk -F'[: ]' ' {if (/^[az]/) printf $1 \" \"} {if (/inet addr:/) print $4 }' ", { user: 'user', host: hostAddress, password: 'password' }).pipe(process.stdout) }; 

输出是

 enp0s3 192.168.1.8 enp0s3 192.168.1.9 

尝试这样做,如果你不想使用pipe道。 它仍然是asynchronous的,所以如果你想从函数中返回这个数据的话,至less要使用类似callback或者承诺的东西。

 exec("ifconfig -a | tr -s ' ' | awk -F'[: ]' ' {if (/^[az]/) printf $1 \" \"} {if (/inet addr:/) print $4 }' ", { user: 'user', host: hostAddress, password: 'password' }).on('data', function(data) { console.log('data:', data); // parse and push items onto an array }).on('end', function() { // no more data will be coming in // resolve your promise with the array, // or pass it in to your callback from here }); 

你想看看stream接口,特别是可读的。