PHP如何在执行bash脚本后从远程网关输出错误消息

时间:2017-08-28 22:34:41

标签: php bash

我有一个简单的PHP函数,可以根据用户选择的单选按钮选项调用远程网关,并提交调用脚本(up.sh或down.sh)。我能够从远程网关成功运行脚本,但是,每当出现问题时,我的网页都不会显示错误。有没有办法在网页上回应错误?

testexe.php

if ($_SERVER['REQUEST_METHOD'] == 'POST'){    
  //create the ssh connection
      if ($connection = @ssh2_connect($gateway, 22)) {
           ssh2_auth_password($connection, $gwUser, $gwPwd);
           if(isset($_POST['option']) && $_POST['option'] == 1) { 
                $stream = ssh2_exec($connection, "/home/user/aust/up.sh");
                stream_set_blocking($stream, true);
                $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
                echo '<pre>' . stream_get_contents($stream_out) . '</pre>';

           }

           if(isset($_POST['option'])  && $_POST['option'] == 2) { 
                $stream = ssh2_exec($connection, "/home/user/aust/down.sh");
                stream_set_blocking($stream, true);
                $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
                echo '<pre>' . stream_get_contents($stream_out) . '</pre>';
           }
     }
}

up.sh

#!/bin/bash
echo 'expect -f ./scripts/myExpectScript.exp' //I can see this on the webpage
expect -f ./scripts/myExpectScript.exp //this throws an error but i dont see the error on the page.
echo

错误输出:

expect -f ./scripts/myExpectScript.exp
couldn't read file "./scripts/myExpectScript.exp": no such file or directory //I want to see this on the webpage.

1 个答案:

答案 0 :(得分:1)

你正在使用标志SSH2_STREAM_STDIO,当事情按预期工作时,它会给你一个结果。如果出现问题,我认为您需要标记SSH2_STREAM_STDERR

请参阅ssh2_fetch_streamhttp://php.net/manual/en/function.ssh2-fetch-stream.php

预定义常量SSH2_STREAM_STDERRhttp://php.net/manual/en/ssh2.constants.php