1

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 2

3

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)}) 
Sign up to request clarification or add additional context in comments.

6 Comments

You can remove the privatekey parameter @Nandini
getting an error like this: (node:584) UnhandledPromiseRejectionWarning: Error: config.privateKey must be a string
Means I just created new file and tried to run the above code.
var path, node_ssh, ssh, fs fs = require('fs') path = require('path') node_ssh = require('node-ssh') ssh = new node_ssh() ssh.connect({ host: '192.168.0.159', username: 'hduser1', password: '123' //privateKey: fs.readFileSync('C:/Users/NANDINI CHITTI/Desktop/Migration Tool/id_rsa') }) .then(function() {}) console.log('SSH connecting....') this the code
Thank you @shubh . I got it. and if I want to run any commands How do I do that
|
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.