从stdout读书

时间:2016-04-05 06:09:56

标签: javascript node.js

我正在使用ssh-exec npm,我希望获得远程ssh命令的结果,解析它并将其存储到数组中。它被用管道传输到stdout,我不知道如何将它变成变量。

function GetRemoteLinuxIp(hostAddress) {
  console.log(hostAddress);

  exec("ifconfig -a | tr -s ' ' | awk -F'[: ]' '  {if (/^[a-z]/) 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

1 个答案:

答案 0 :(得分:1)

如果您不想使用管道,请尝试这样做。它仍然是异步的,所以如果你想从函数中返回这些数据,你必须至少使用类似回调或承诺的东西。

exec("ifconfig -a | tr -s ' ' | awk -F'[: ]' '  {if (/^[a-z]/) 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
});

您想要查看streams界面,特别是可读的界面。