2

我有一个使用 ssh2 npm 模块和 readline 的简单交互式 ssh 客户端。在每一行我将数据发送到服务器流,但由于某种原因输入的命令也发送

var Client = require('ssh2').Client;
var readline = require('readline')

var conn = new Client();
conn.on('ready', function() {
  console.log('Client :: ready');
  conn.shell(function(err, stream) {
    if (err) throw err;
    // create readline interface
    var rl = readline.createInterface(process.stdin, process.stdout)

    stream.on('close', function() {
      process.stdout.write('Connection closed.')
      console.log('Stream :: close');
      conn.end();
    }).on('data', function(data) {
      // pause to prevent more data from coming in
      process.stdin.pause()
      process.stdout.write('DATA: ' + data)
      process.stdin.resume()
    }).stderr.on('data', function(data) {
      process.stderr.write(data);
    });

    rl.on('line', function (d) {
      // send data to through the client to the host
      stream.write(d.trim() + '\n')
    })

    rl.on('SIGINT', function () {
      // stop input
      process.stdin.pause()
      process.stdout.write('\nEnding session\n')
      rl.close()

      // close connection
      stream.end('exit\n')
    })

  });
}).connect({
        host: 'www58.lan',
        port: 22,
        username: 'gorod',
        password: '123qwe'
});

但是每个输入的命令都是重复的。如何做到没有重复?谢谢!

输出:

gorod@www58:~$ ls
ls
temp.sql                       yo              sm_www94
a.out                          sm_dev1017      System Volume Information
dump20180801                   sm_qa1017       www58_sm_2310
dumps                          sm_www58
gorod@www58:~$

预期输出:

gorod@www58:~$ ls
temp.sql                       yo              sm_www94
a.out                          sm_dev1017      System Volume Information
dump20180801                   sm_qa1017       www58_sm_2310
dumps                          sm_www58
gorod@www58:~$
4

1 回答 1

3

当前ssh2不支持在为交互式 shell 会话设置伪 TTY 时传递终端模式(例如禁用远程终端回显),尽管ssh2-streams已经支持它。

在将该功能添加到 之前ssh2,至少有两种可能的解决方法:

  1. 自动写入'stty -echo\n'一次 shell 流。这将有效地做与从一开始就禁用远程终端回显相同的事情,除了 stty 命令本身将被回显。

  2. 用于process.stdin.setRawMode(true)禁用本地回显并仅接收远程终端回显。但是,这有两个缺点:远程终端回显可能会延迟(导致混乱),并且您将无法通过'SIGINT'事件处理程序捕获 ctrl-c(这可能是一个功能,因为它将透明地将 ctrl-c 分派到而是远程服务器,这在某些情况下可能很有用)。

于 2018-12-11T14:53:07.610 回答