Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs execute command on remote linux server

Tags:

node.js

From nodejs I have been trying to execute linux commands on remote server and get the output in stream for further processing. For connecting to remote linux server , I have all necessary details like serverip, username and password. I searched a lot on internet and found that this can be achieved by ssh.

Can Nodejs ui page run shell cmd to remote machine and run script

But this answer a bit confusing and I didn't get how to use password in connection.

Pointer to any working example would be great help.

like image 404
usersam Avatar asked May 29 '18 14:05

usersam


Video Answer


1 Answers

I solved the problem myself. There is one npm package (ssh-exec) available for ssh command execution. Below is the code I used.

var exec = require('ssh-exec')
var v_host = 'XX.XX.XX.XXX'
exec('ls -lh', {
  user: 'root',
  host: 'XX.XX.XX.XXX', 
  password: 'password'
}).pipe(process.stdout , function (err, data) {
    if ( err ) { console.log(v_host); console.log(err); }
  console.log(data)
})
like image 54
usersam Avatar answered Nov 01 '22 01:11

usersam