简体   繁体   English

node.js ssh2 => 如何关闭连接和处理 ECONNRESET 错误

[英]node.js ssh2 => how to close connection and handle ECONNRESET error

In a node.js project, I have installed and configured OPENSSH on a remote windows machine and trying to execute commands from local windows server using ssh2 (latest version) package. There is one exe file on remote machine which keeps on running until use cancel the execution.在一个 node.js 项目中,我在一台远程 windows 机器上安装并配置了 OPENSSH,并尝试使用 ssh2(最新版本)package 从本地 windows 服务器执行命令。远程机器上有一个 exe 文件一直运行直到使用取消执行.

Here is my route file code to serve user request.这是我的路由文件代码来满足用户请求。

const express = require('express');
const Route = express.Router();
var Client = require('ssh2').Client;
var conn = new Client();

Route.route('/start').get(function(req, res) {

    var v_host = 'xxx.xxx.xxx.xx';
    var v_user = 'Administrator';
    var v_pass = 'password';

    conn.on('ready', function() {
        console.log('Client :: start-ready');
        conn.exec('C:\\Work\\echousers.exe', function(err, stream) {
            if (err) {
                console.log('FIRST :: forwardOut error: ' + err);
                return conn.end();
            }
            stream.on('close', function(code, signal) {
                console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
                conn.end();
            }).on('data', function(data) {
                console.log('connname :' + data);
            });
        });
    }).connect({
        host: v_host,
        port: 22,
        username: v_user,
        password: v_pass
    });

    res.end();
});

Route.route('/stop').get(function(req, res) {
    //conn.destroy();
    conn.end(); 

    res.end();
});

module.exports = Route; 

It works on start request and "start" the batch execution but when i send "stop" request it throws error and crashes the node server.它适用于启动请求并“启动”批处理执行但是当我发送“停止”请求时它会抛出错误并使节点服务器崩溃。

events.js:174
      throw er; // Unhandled 'error' event
      ^

Error: read ECONNRESET
    at TCP.onStreamRead (internal/stream_base_commons.js:111:27) 
Emitted 'error' event at:
    at Socket.<anonymous> (D:\work\angular\app\server\node_modules\ssh2\lib\client.js:307:10)
    at Socket.emit (events.js:189:13)
    at emitErrorNT (internal/streams/destroy.js:82:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)    
    at process._tickCallback (internal/process/next_tick.js:63:19)
[nodemon] app crashed - waiting for file changes before starting...

Please help me to handle this error.请帮我处理这个错误。 Struggling for many days to resolve this error.挣扎了很多天来解决这个错误。 Many thanks in advance.提前谢谢了。

You need to add error handling:您需要添加错误处理:

conn.on('error', function(err) {
        //Handle Error here
})

I had the same issue.我遇到过同样的问题。 The SSH2 error handling does not go through standard event emission. SSH2 错误处理不会通过标准事件发射 go。

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

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