2

I am currently working on rebuilding our internal CLI tools as a command-line Node application. Part of this involves rebuilding the bash script to SSH into a specific server part of this app.

I know how to use child_process's spawn function to actually execute SSH, but this does not yield the same result as just SSH'ing in the shell directly (even when using flag -tt on the ssh command). For one, typed commands are shown on the screen twice and trying to use nano on these remote machines does not work at all (screen size is incorrect, only takes up about half of the console window, and using arrows does not work).

Is there a better way to do this in a node app? This is the general code I currently use to start the SSH session:

run: function(cmd, args, output) {
    var spawn = require('child_process').spawn,
        ls = spawn(cmd, args);

    ls.stdout.on('data', function(data) {
        console.log(data.toString());
    });

    ls.stderr.on('data', function(data) {
        output.err(data.toString());
    });

    ls.on('exit', function(code) {
        process.exit(code);
    });

    process.stdin.resume();
    process.stdin.on('data', function(chunk) {
        ls.stdin.write(chunk);
    });

    process.on('SIGINT', function() {
        process.exit(0);
    });
}
1
  • I made a module for that ssh2-client Commented Jan 3, 2017 at 12:09

1 Answer 1

3

You can use the ssh2-client package

const ssh = require('ssh2-client');

const HOST = 'junk@localhost';

// Exec commands on remote host over ssh
ssh
  .exec(HOST, 'touch junk')
  .then(() => ssh.exec(HOST, 'ls -l junk'))
  .then((output) => {
    const { out, error } = output;
    console.log(out);
    console.error(error);
  })
  .catch(err => console.error(err));

// Setup a live shell on remote host
ssh
  .shell(HOST)
  .then(() => console.log('Done'))
  .catch(err => console.error(err));

DISCLAIMER : I'm the author of this module

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.