简体   繁体   中英

Using the Node module SSH2 with shell

My aim is to make a web application that allows it's user to connect to an SSH server remotely, ie without installing an SSH client on their computer. So this means my server will be an intermediate interface between the user and their SSH server/s.

I found an SSH2 module for node: https://github.com/mscdex/ssh2

I figured the most appropriate method of connecting was using the shell() method.

The following is a basic attempt to get a shell working.

var Connection = require('ssh2');

var c = new Connection();

c.on('ready', function() {
   c.shell(onShell);
});

var onShell = function(err, stream) { 
    if (err != null) {
        console.log('error: ' + err);
    }

    stream.on('readable', function() {
        var chunk;
        while (null !== (chunk = stream.read())) {
            console.log('got %d bytes of data', chunk.length);
        }
    });

    stream.write('ls\r\n');

    console.log('Shell');

}

c.connect({
    host: 'localhost',
    port: 22, 
    username: 'matt',
    password: 'password'
});

It connects fine, and there are no errors, but the "got %d bytes of data" does not show. How can I fix this?

Furthermore would this method be sensible in a large scale application with potentially many simultaneous different connections?

ssh2 currently does not use streams2 yet because things get tricky because of the two (stdout and stderr) "sub-"streams and trying to handle backpressure in a sane way. I am still hoping I can find some solution via streams2 though.

For now, you will have to listen for 'data', 'drain', etc. events instead.

UPDATE: ssh2 v0.3.x now supports streams2.

I wrote a wrapper class for ssh2 that handles running multiple commands in a SSH shell session and can SSH tunnel to multiple hosts using nested host objects. Each hosts config object has its own commands, command event handlers, end of session handler and authentication parameters. Commands responses can be checked for prompts or results that require extra handling or addition/removal of commands from a commands array. It also times out if a command produces an unexpected prompt that is not handled and would normally cause the process to hang waiting for a response it will never get.

Check it out:

Extensive info in the readme, test examples provided, additional info in the git wiki. https://www.npmjs.org/package/ssh2shell

https://github.com/cmp-202/ssh2shell

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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