1

What i have

This is working but i want to get result of long running scripts

Start the sh script and then calling an ajax funciton which is checking every 2 sec and show the result. is this possible?

$connection = ssh2_connect('192.168.1.1', 22);
ssh2_auth_password($connection, 'user', 'password');
$stream = ssh2_exec($connection, 'sh /test.sh');

stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);

echo stream_get_contents($stream_out);

What i will

$connection = ssh2_connect('192.168.1.1', 22);
ssh2_auth_password($connection, 'user', 'password');
$stream = ssh2_exec($connection, 'sh /test.sh');
$session->stream = $stream;  <-##### Here i save it in a session ###### 

########################################################
I want to save the Stream in a session variable 
and check the result anytime while the process is still running 
Is this possible ?
##########################################################

$stream = $session->stream;   <-##### Here i get it from the session ######  
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);

echo stream_get_contents($stream_out);

When i do this i get the follwing error:

stream_set_blocking() expects parameter 1 to be resource, integer given
Moenie
  • 113
  • 2
  • 9
  • What you're wanting can't be done. Among other things, resources can't be saved to sessions per http://stackoverflow.com/a/6078862/569976 – neubert Oct 27 '14 at 13:51

1 Answers1

2

Ok i understand its impossible.

My solution is:

Run the script on background and write the results in a output.txt

$stream = ssh2_exec($connection, 'sh /test.sh > output.txt &');

And read the output file every 2 sec so i can follow the process. at the end of the script it will echo "ProcessFinished" so with this flag you know its finished with running and you dont have to check the output.txt anymore.

$stream = ssh2_exec($connection, "cat output.txt");

stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
$processStatus = stream_get_contents($stream_out);
echo $processStatus;

EDIT:
If you also want the errors you can put 2>&1 at the end

$stream = ssh2_exec($connection, 'sh /test.sh > output.txt 2>&1 &');
Moenie
  • 113
  • 2
  • 9
  • 1
    using the the `tail` command rather than `cat` is a more general answer, also you are only redirecting the `stdout` to the file `output.txt`, `stderr` will not be captured – MichaelStoner Oct 29 '14 at 08:07
  • now you can also get the errors in the output file. I use Cat because i want the all file content not only the last row. – Moenie Oct 29 '14 at 08:52
  • cool, often a log of progress can be many, many line or pages, so you could often use 'tail -n 50' to show the last 50 lines etc – MichaelStoner Oct 29 '14 at 16:26