Search code examples
node.jsssh

How to establish an SSH connection using Node.js


I want to make an SSH connection using Node.js or JavaScript so that I connect it through a web page and run the commands. How can I do this?


Solution

  • There is a very good library, node-ssh. It supports promises too. Have a look at that.

    Code copied from the official documentation:

    var path, node_ssh, ssh, fs
    
    fs = require('fs')
    path = require('path')
    node_ssh = require('node-ssh')
    ssh = new node_ssh()
    
    ssh.connect({
        host: 'localhost',
        username: 'steel',
        privateKey: '/home/steel/.ssh/id_rsa'
    })
    

    Or

    ssh.connect({
        host: 'localhost',
        username: 'steel',
        privateKey: fs.readFileSync('/home/steel/.ssh/id_rsa')
    })
        .then(function() {})
    

    Edit-I have tried this code in my system and its working

    var path, node_ssh, ssh, 
    fs 
    fs = require('fs') 
    path = require('path') 
    node_ssh = require('node-ssh') 
    ssh = new node_ssh() 
    ssh.connect(
        { host: 'Your host', username: 'username', password: 'yourpass', 
     }) 
    .then(function(response) {console.log(response)})