【发布时间】:2016-07-23 19:50:26
【问题描述】:
我将 bash 脚本作为字符串存储在 db 中,我需要根据用户需求调用它。脚本应该从 php 级别在远程机器上执行。我找到了以下主题:
关于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 user@server 'bash -s' < test");
chdir($old_path);
or
$old_path = getcwd();
chdir('/path_to_script_directory');
$output = shell_exec("ssh user@server 'bash -s' < ".$script);
chdir($old_path);
//result => output = null
在上面的例子中,我用“test”脚本和字符串脚本($script 变量)尝试了两种情况。我更喜欢第二种选择。两种情况都包含简单的脚本:
#!/bin/bash
ifconfig
提前谢谢你!
【问题讨论】:
-
您的尝试结果如何?遇到了哪些错误/问题?
-
我在两个示例之后的注释“//”中写了结果
-
您能否通过查看远程服务器上的身份验证日志来确认您的 SSH 连接是否成功?