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?
turns out the single quotes around the remote command were the problem.
var args = ["[email protected]", "ls -lai"];
and it works
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With