0
我将bash脚本存储为db中的字符串,我需要根据用户需求调用它。脚本应该在远程机器上从php级别执行。我发现了以下主题:如何在远程服务器上使用php运行本地bash脚本
两个约ssh连接主题和调用远程脚本:
- How to use SSH to run a shell script on a remote machine?
- https://serverfault.com/questions/241588/how-to-automate-ssh-login-with-password
而且两种方式在PHP中使用它:
- Run Bash Command from PHP
- get result from ssh2_exec, http://php.net/manual/en/function.ssh2-exec.php
我试着用下面的代码在我的Symfony2应用:
第一次尝试:
$connection = ssh2_connect('IP_ADDRESS', 22);
ssh2_auth_password($connection, 'user', 'password');
$stream = ssh2_exec($connection, "'bash -s' < ".$script);
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
$output = stream_get_contents($stream_out);
//result => output = empty string
二:
$old_path = getcwd();
chdir('/path_to_script_directory');
$output = shell_exec("ssh [email protected] 'bash -s' < test");
chdir($old_path);
or
$old_path = getcwd();
chdir('/path_to_script_directory');
$output = shell_exec("ssh [email protected] 'bash -s' < ".$script);
chdir($old_path);
//result => output = null
作为例子上面我用“测试”脚本尝试了两个例子pt和字符串脚本($ script变量)。第二种选择是由我优先。两种情况都包含简单的脚本:
#!/bin/bash
ifconfig
提前致谢!
什么是你尝试的结果吗?遇到什么错误/问题? – TenG
在两个示例之后,我在评论“//”中写了结果 – Krzychu
您是否可以通过检查远程服务器上的验证日志来确认SSH连接是否成功? – ghoti