【问题标题】:PHP: SSH connection and python script executionPHP:SSH连接和python脚本执行
【发布时间】:2017-04-10 11:41:20
【问题描述】:

我的前端有一个按钮,这个按钮与后端对话。 后端正在启动一个远程脚本:

<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$connection = ssh2_connect('192.168.56.180', 22);
ssh2_auth_password($connection, 'root', 'password');
$stream = ssh2_exec($connection, 'python /WATSON/APP/test/testlistrbk.py');
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo $stream_out_contente;
fwrite($myfile, $stream_out);
fclose($myfile);
?> 

我有 2 个问题,第一个,php 应该等待 python 脚本完成,因为它说 here 但它没有。

第二个,它给了我以下内容:

PHP 警告:fwrite() 期望参数 2 是字符串,资源在 /var/www/html/WEBAPP/wa_start.php 第 41 行给出

【问题讨论】:

  • var_dump($stream_out);的输出放在fwrite之前

标签: php python ssh


【解决方案1】:

使用stream_get_contents(stream_out);

在您的代码 $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO); 中,这将返回 resource 而不是字符串输出。试试这个代码。

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");

$connection = ssh2_connect('192.168.56.180', 22);
ssh2_auth_password($connection, 'root', 'password');
$stream = ssh2_exec($connection, 'python /WATSON/APP/test/testlistrbk.py');

stream_set_blocking($stream, true);

$outputStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);

echo "Output: " . stream_get_contents($outputStream);
echo "Error: " . stream_get_contents($errorStream);

fwrite($myfile, $outputStream.$errorStream);
fclose($myfile);

【讨论】:

  • @MouIdri 请检查$stream_out 将收到来自$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
  • @Mouldri 你只需要用我的代码替换你代码的最后三行。
  • 对不起,我没有看到丢失的 $.. 我更改了它,我不再有错误消息,。但是行为很奇怪,因为没有写入文件(我 chmoded 0777,所以这不是版权问题)。
  • @MouIdri 我正在更新我的帖子,然后你可以查看
  • @MouIdri 试试这个代码,看看它是否工作正常你也可以参考这个php.net/manual/en/function.ssh2-exec.php#99089
猜你喜欢
  • 2018-11-30
  • 1970-01-01
  • 1970-01-01
  • 2016-09-30
  • 2017-06-29
  • 1970-01-01
  • 1970-01-01
  • 2019-01-05
相关资源
最近更新 更多