简体   繁体   English

从节点脚本打开交互式SSH会话

[英]Open interactive SSH session from Node script

I am currently working on rebuilding our internal CLI tools as a command-line Node application. 我目前正在将内部CLI工具重建为命令行节点应用程序。 Part of this involves rebuilding the bash script to SSH into a specific server part of this app. 其中一部分涉及将bash脚本重建为SSH到此应用程序的特定服务器部分。

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). 我知道如何使用child_processspawn函数实际执行SSH,但这不会产生与仅在外壳中直接进行SSH相同的结果(即使在ssh命令上使用标志-tt时)。 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). 首先,键入的命令会在屏幕上显示两次,并且试图在这些远程计算机上使用nano根本不起作用(屏幕大小不正确,仅占用了控制台窗口的一半,并且使用箭头不起作用)。

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: 这是我当前用于启动SSH会话的常规代码:

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 您可以使用ssh2-client软件包

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 免责声明:我是这个模块的作者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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