【问题标题】:Open interactive SSH session from Node script从节点脚本打开交互式 SSH 会话
【发布时间】:2017-01-03 20:11:44
【问题描述】:

我目前正在将我们的内部 CLI 工具重新构建为命令行节点应用程序。其中一部分涉及将 bash 脚本重建为 SSH 到此应用程序的特定服务器部分。

我知道如何使用child_processspawn 函数来实际执行SSH,但这不会产生与直接在shell 中执行SSH 相同的结果(即使在@ 上使用标志-tt 987654325@ 命令)。一方面,输入的命令在屏幕上显示两次,在这些远程机器上尝试使用nano 根本不起作用(屏幕大小不正确,只占控制台窗口的大约一半,使用箭头不起作用) .

在节点应用程序中是否有更好的方法来执行此操作?这是我目前用来启动 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);
    });
}

【问题讨论】:

标签: node.js bash unix ssh


【解决方案1】:

您可以使用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));

免责声明:我是这个模块的作者

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-15
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 2010-09-11
    • 2012-11-23
    • 1970-01-01
    相关资源
    最近更新 更多