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?
2 Answers
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)})
6 Comments
If you're using Node.js to SSH into a server, you have a couple of solid options: ssh2 and hivessh. ssh2 has a callback approach that can be unmaintainable and ugly if you use a lot of nested or dependent ssh operations.
Hivessh is an ssh2 wrapper that provides a promise based approach with some nice utilities. like checking if a command exists.
https://github.com/NobleMajo/hivessh https://github.com/mscdex/ssh2