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.

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);