Nodejs ssh2 exec执行shell超时终止执行

使用ssh2 模块执行shell的时候,只有在连接目标机器时,有个readyTimeout用于设置ssh连接目标机器的超时终止的参数。

conn.connect({
    host: ip,
    port: 22,
    username: user,
    password: password,
    readyTimeout: 5000
});

没有用于设置shell执行的超时的参数,但是我的shell命令在机器负载高的情况下返回时间需要很久很久,需要超过一定时间需要终止掉shell。
看了github别人提得issue也没有很好的解决办法,后来用了个取巧的办法如下

解决办法

方法也是蛮简单,结合系统提供的shell命令timeout
例子:

timeout 2s pwd
var Client = require('ssh2').Client;

var conn = new Client();
conn.on('ready', function() {
        var command = 'source ~/.bash_profile;timeout 2s pwd'
        conn.exec(command, function(err, stream) {
            if (err) throw err;
            stream.on('close', function(code, signal) {
                conn.end();
            }).on('data', function(data) {

            });
        });
    }).on('error', function(err) {

    })
    .connect({
        host: currentHost.host,
        port: currentHost.port,
        username: currentHost.username,
        password: currentHost.password
        readyTimeout: 5000
    });

猜你喜欢

转载自blog.csdn.net/a19891024/article/details/76560072