Slack Groverglow
Slack Groverglow

Reputation: 856

Reading from stdout

I'm using ssh-exec npm and I want to get the the result of a remote ssh command, parse it, and store it into an array. It's being piped to stdout instead, and I'm not sure how to get it into a variable.

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)
};

the output is

enp0s3 192.168.1.8
enp0s3 192.168.1.9

Upvotes: 2

Views: 108

Answers (1)

dvlsg
dvlsg

Reputation: 5538

Try doing this, if you don't want to use pipes. It's still going to be asynchronous, so you'll have to at least use something like a callback or promise if you're looking to return this data from the function.

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
});

You want to take a look at the streams interface, specifically the readable one.

Upvotes: 1

Related Questions