所以我做了一件简单的事情,首先我通过 ssh2_exec (成功验证后)执行命令,然后读取变量中的答案。我的代码如下(未经身份验证)
try {
$stdout_stream = ssh2_exec($this->connection, $_cmd);
$stderr_stream = ssh2_fetch_stream($stdout_stream, \SSH2_STREAM_STDERR);
} catch (Exception $e) {
$std_output = $e->getMessage();
return false;
}
$output = "";
while (!feof($stdout_stream)) {
$output .= fgets($stdout_stream, 4096);
}
while (!feof($stderr_stream)) {
$output .= fgets($stderr_stream, 4096);
}
fclose($stdout_stream);
fclose($stderr_stream);
return $output;
Run Code Online (Sandbox Code Playgroud)
例如我尝试执行这样的 cmd:
sudo service httpd stop && sudo service httpd start
Run Code Online (Sandbox Code Playgroud)
因此,当命令执行良好时,一切都很好,响应是
关闭 httpd: [ OK ] 启动 httpd: [ OK ]
但是当我尝试在没有 sudo 的情况下执行这样的命令时
service httpd stop && service httpd start
Run Code Online (Sandbox Code Playgroud)
我知道服务器说类似“找不到命令”或类似的内容,但我无法收到此错误,此脚本无限执行。 …
我正在用 Node.js 编写一个微服务,它运行一个特定的命令行操作来获取特定的信息。该服务在多个服务器上运行,其中一些在 Linux 上,一些在 Windows 上。我正在使用ssh2-exec连接到服务器并执行命令,但是,我需要一种方法来确定服务器的操作系统以运行正确的命令。
let ssh2Connect = require('ssh2-connect');
let ssh2Exec = require('ssh2-exec');
ssh2Connect(config, function(error, connection) {
let process = ssh2Exec({
cmd: '<CHANGE THE COMMAND BASED ON OS>',
ssh: connection
});
//using the results of process...
});
Run Code Online (Sandbox Code Playgroud)
我有一个解决方案的想法:按照这个问题,预先运行一些其他命令,并从所述命令的输出中确定操作系统;但是,我想了解是否有更“正式”的方式来实现这一点,特别是使用SSH2库。