简体   繁体   中英

Open interactive SSH session from Node script

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM