简体   繁体   English

带有nodejs child_process的ssh,在服务器上找不到命令

[英]ssh with nodejs child_process, command not found on server

I'm attempting to run a simple ssh command, via nodejs child_process. 我试图通过nodejs child_process运行一个简单的ssh命令。 when i run the command via nodejs code, it fails saying the command that i sent to the server was not found. 当我通过nodejs代码运行命令时,它无法说我找不到发送到服务器的命令。 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 user@example.com 'ls -lai'

and here is the nodejs version of the same ssh command, using child_process 这是使用child_process的同一个ssh命令的nodejs版本

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

var command = "ssh";
var args = ["user@example.com", "'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). 但是当我运行这个nodejs代码来执行相同的命令时,stderr回调代码启动,命令返回代码127(找不到命令)。

$ 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. 根据这里的输出,找不到'ls -lai'命令......但这没有意义,因为当我从终端提示符直接运行它时它完全正常。

anyone know why running ssh through nodejs would cause this to happen? 有谁知道为什么通过nodejs运行ssh会导致这种情况发生?

turns out the single quotes around the remote command were the problem. 事实证明,远程命令周围的单引号是问题所在。

var args = ["user@example.com", "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 = ["user@example.com", "'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: 但是,您仍然可以省略引号,并且所有内容都将通过SSH正确执行,因为child_process将它作为单个参数传递:

var args = ["user@example.com", "cd ~ && ls -lai"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM