Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ssh with nodejs child_process, command not found on server

I'm attempting to run a simple ssh command, via nodejs child_process. when i run the command via nodejs code, it fails saying the command that i sent to the server was not found. when i run the same command just copy & pasting to my terminal window, it runs fine.

here is the command line version of what i'm trying to do :

ssh [email protected] 'ls -lai'

and here is the nodejs version of the same ssh command, using child_process

var cproc = require('child_process');
var exec = cproc.exec;
var spawn = cproc.spawn;

var command = "ssh";
var args = ["[email protected]", "'ls -lai'"];

var child = spawn(command, args);

child.stdout.on('data', function(data) {
  console.log('stdout: ' + data);
});

child.stderr.on('data', function(data) {
  console.log('stderr: ' + data);
});

child.on('close', function(code) {
  console.log('exit code: ' + code);
  process.exit();
});

the output from the command line version is exactly what i expect... i get the directory listing. but when i run this nodejs code to execute the same command, the stderr callback code kicks in, and the command returns code 127 (command not found).

$ node test-ssh.js 
stderr: bash: ls -lai: command not found

exit code: 127

according to the output here, the 'ls -lai' command is not found... but that doesn't make sense, as it works perfectly fine when i run this from my terminal prompt directly.

anyone know why running ssh through nodejs would cause this to happen?

like image 785
Derick Bailey Avatar asked Dec 27 '14 19:12

Derick Bailey


2 Answers

turns out the single quotes around the remote command were the problem.

var args = ["[email protected]", "ls -lai"];

and it works

like image 67
Derick Bailey Avatar answered Oct 19 '22 03:10

Derick Bailey


I had this problem too but I thought the quotes were a necessity for me due to me trying to run multiple commands at once, and I kept trying to find a way around it.

For example:

var args = ["[email protected]", "'cd ~ && ls -lai'"]

would break. However, you can still omit the quotes and everything will execute correctly through SSH since child_process will pass it as a single argument:

var args = ["[email protected]", "cd ~ && ls -lai"]
like image 23
sjagr Avatar answered Oct 19 '22 03:10

sjagr