我有一个简单的交互式 ssh 客户端,使用 ssh2 npm 模块和 readline。在每一行上,我都将数据发送到服务器流,但由于某种原因,输入的命令也发送了
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:~$
最佳答案
目前,ssh2
在为交互式 shell session 设置伪 TTY 时不支持传递终端模式(例如禁用远程终端回显),尽管 ssh2-streams
> 已经支持了。
在将该功能添加到 ssh2
之前,至少有两种可能的解决方法:
自动将
'stty -echo\n'
写入 shell 流一次。这将有效地完成与从一开始就禁用远程终端回显相同的操作,除了 stty 命令本身将被回显。使用
process.stdin.setRawMode(true)
禁用本地回显并仅接收远程终端回显。然而,这有两个缺点:远程终端回显可能会延迟(导致困惑),并且您将无法通过'SIGINT'
事件处理程序捕获 ctrl-c(这可能是一个功能)因为它会透明地将 ctrl-c 分派(dispatch)到远程服务器,这在某些情况下很有用)。
关于node.js - Node ssh2 客户端中的重复数据输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53715560/