dtcu5885 2014-12-13 17:20
浏览 63

PHP-运行远程SSH脚本并将结果打印在网页中

First of all PHP is nowhere near my forte but I’m determined to learn. I’ve probably not been assigned the easiest of tasks for a first PHP project so bear with me whilst I try and explain. I want to within a simple form enter a server name, click submit and the following to occur there after:

  1. Copy a script
  2. Execute the script
  3. Return the results

Rather than tackle it all in one chunk, It made sense (to me) to break it down and start small:

<?php

$conn = ssh2_connect('10.x.x.x', 22);
ssh2_auth_password($conn, 'user', 'password');

ssh2_scp_send($conn, '/path/to/script', '/path/to/script', 0700);

$stream = ssh2_exec($conn, '/path/to/script');
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo stream_get_contents($stream_out);

?>

# php –f name-of-script.php

This worked fine from the command line and the expected response was returned.

I wanted to extend this and have the same functionality within a browser so I created a simple form as follows:

<form action="name-of-script.php" method="POST">
Server Name: <input type="text" name="node" size="20">
<input type="submit" value="Submit">
</form> 

Then altered my code slightly:

<?php

$node = $_POST["node"];

$conn = ssh2_connect($node, 22);
ssh2_auth_password($conn, 'user', 'password');

ssh2_scp_send($conn, '/path/to/script', '/path/to/script', 0700);

$stream = ssh2_exec($conn, '/path/to/script');
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo stream_get_contents($stream_out);

?>

Have I made a fundamental mistake by expecting all the SSH2 functions to produce the same result as the command line within a browser? All I see at the moment is a blank page after entering the server name and clicking submit.

  • 写回答

1条回答 默认 最新

  • doupin5408 2014-12-17 22:13
    关注

    A complete school boy error on my part! The file I was dealing with was suffixed .html not .php! Once I renamed the file all was well.

    Working Code:

    $conn = ssh2_connect('10.x.x.x', 22);
    ssh2_auth_password($conn, 'user', 'password');
    
    ssh2_scp_send($conn, '/path/to/script', '/path/to/script', 0700);
    
    $stream = ssh2_exec($conn, '/path/to/script');
    stream_set_blocking($stream, true);
    $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
    echo stream_get_contents($stream_out);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作