【问题标题】:exec() PHP cannot wait the response (phpseclib)exec() PHP 不能等待响应 (phpseclib)
【发布时间】:2015-05-20 08:02:15
【问题描述】:

我只是尝试使用exec() 命令但它不起作用(我使用 phpseclib)。 这是我的代码

echo $ssh->exec("cd testpath; ./display_test.sh 1 -s 098888888");

结果是

egrep:无法打开 /testpath/test_displaysub.10912.mml

但是当我用 read() 运行时,用这段代码 write()

$ssh->setTimeout(5);
$ssh->read();
$ssh->write("cd testpath \n");
$ssh->read();
$ssh->write("./display_test.sh 1 -s 098888888 \n");
echo $ssh->read();

它有效。我想使用命令exec(),因为它不使用超时。 我认为 exec() 命令是错误的,可能是它没有等待响应或跳过该文件(./display_test.sh) 中的某些命令,因为我的代码有

sendCommand (){
    cat $templateLogout >> ${FILE}
    $scriptfile < ${FILE} 1> $processfile 2> tmp #led $processfile to run other
}

checkTimeout(){
    timeout=$(grep "Timed out" tmp|wc -l)
    if [ $timeout -gt 0 ]
    then
        Result="Connection Lost."
        index_timeout=1
    fi
    rm tmp
}

getResult (){
    Result= egrep "response" $mmlfile .........(have more)

当我使用 exec() 它创建 $processfile 但在 $processfile 中不等待完成运行然后它会跳过执行 checkTimeout()getResult () 这是它不能 egrep 我认为的原因。 如果我觉得不对,请告诉我。

如果我想使用命令exec(),请告诉我该如何处理这个问题。

注意! 我真的不使用超时,因为我的项目可以输入文件并且我不知道该过程要执行多少次 在我的文件中可以

0988888888
0988888887
0988888886

还有我的脚本./display_test.sh 1 -f filename \n

【问题讨论】:

  • $ssh-&gt;write("cd cd testpath \n"); 这是您“工作”代码中的实际行吗?该行将失败,因此以下命令将在与您可能期望的不同的工作目录中执行。
  • 很抱歉,我实际上使用了“cd testpath \n”,但我输入错误。 exec() 不等待我的回复这个问题我该怎么办

标签: php shell ssh exec phpseclib


【解决方案1】:

您不必对 read() / write() 使用超时。试试这个:

$ssh->read('[prompt]');
$ssh->write("cd testpath \n");
$ssh->read('[prompt]');
$ssh->write("./display_test.sh 1 -s 098888888 \n");
echo $ssh->read('[prompt]');

[prompt] 是一个占位符 - 使用您的实际提示符。

W.r.t. $ssh-&gt;exec...也许尝试做$ssh-&gt;enablePTY(); $ssh-&gt;exec(); echo $ssh-&gt;read()

【讨论】:

  • 我尝试遵循您的建议,但如果我使用"[prompt]" without "timeout",它仍在运行,输出不会出现或致命错误:超过 30 秒的最大执行时间。我试试这个你建议我的$ssh-&gt;enablePTY(); echo $ssh-&gt;exec("cd testpath; ./display_test.sh 1 -s 098888888"); 这也不起作用,因为输出结果是“1”我该怎么办。非常感谢。
  • 我真的不使用超时,因为我的项目可以输入文件,我不知道该过程要执行多少次在我的文件中可以是 0988888888 0988888887 0988888886 和我的脚本./display_test.sh 1 -f 文件名\n
  • @pinkypink - 在$ssh-&gt;exec() 之后尝试echo $ssh-&gt;read()$ssh-&gt;read() 不应该阻塞在那里,因为输出确实结束了。这与输出没有结束的交互式 shell 形成对比。也就是说,w.r.t. "[prompt]" without "timeout"... 跟我开玩笑吧。您的提示是什么?在我的系统上是[ec2-user@neubert ~]$。您是否替换了 [prompt] 占位符?
  • 非常感谢您的建议。我可以在没有超时的情况下使用命令读写来做到这一点,但命令 exec() 我使用 $ssh->enablePTY(); $ssh->exec("cd testpath; ./display_test.sh 1 -s 098888888");回声 $ssh->read();但仅使用命令 exec() 具有相同的结果。如果您对此有其他建议,请告诉我,因为如果我使用读写,我必须每次都更改[提示]。谢谢。
  • @neubert 我无法设置 $ssh->setTimeout(3) 因为 shell 在 3 秒后停止... 我的解决方案:1/ 在 .bash_profile 中设置 Unix 常量,具有非功能值,例如:export DO_EXIT_SSH_="IWillNeverSeeThat" 2/ 在 PhpSecLib PHP 代码中,将 "echo $_DO_EXIT_SSH" 添加到原始命令 $cmd = $cmd 。 "; echo $_DO_EXIT_SSH_" 3/ 等待“读取”然后是“IWillNeverSeeThat”值。 $ssh->read("IWillNeverSeeThat");这很好用!
猜你喜欢
  • 2011-10-28
  • 2018-05-31
  • 1970-01-01
  • 2019-01-27
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多