Search code examples
node.jsssh2

What are some examples of "authHandler" in the "connect" client method of the ssh2 npm package?


What are some examples of "authHandler" in the "connect" client method of the ssh2 npm package?

im namely looking to re-order the methods and/or remove some.


Solution

  • Using the documentation, I'm going to try and provide a basic example which include usage of authHandler as mentioned in your question.

    // Require Client Class from ssh2
    const { Client } = require('ssh2');
    
    // Create instance of Client (aka connection)
    const conn = new Client();
    
    // Create our ready event that's called after we connect
    conn.on('ready', () => {
        console.log('Client :: ready');
    });
    
    // Connect with a config object passed in the parameters
    conn.connect({
        host: '192.168.100.100',
        port: 22, // SSH
    
        // Authentication Handler
        authHandler: function (methodsLeft, partialSuccess, callback) {
    
            // Code e.g. get credentials from database
        
            // Once your logic is complete invoke the callback
            // http://npmjs.com/package/ssh2#client-examples
            callback({
                type: 'password',
                username: 'foo',
                password: 'bar',
            });
        }
    });
    

    The above should provide a working example if the credentials are changed. The code can be made slightly cleaner and the calls for conn class can be chained like so:

    conn.on('ready', () => {
        console.log('Client :: ready');
    }).connect({ // Chained
        host: '192.168.100.100',
        port: 22, // SSH
    
        // Authentication Handler
        authHandler: function (methodsLeft, partialSuccess, callback) {
    
            // Code e.g. get credentials from database
        
            // Once your logic is complete invoke the callback
            // http://npmjs.com/package/ssh2#client-examples
            callback({
                type: 'password',
                username: 'foo',
                password: 'bar',
            });
        }
    });