1

I am trying to retrieve a stream of data that comes from an ssh connection. When I use putty to ssh in, I will just start getting data on the screen, no commands were needed.

Now I am trying to do the same thing but in php to manipulate the data and save it to a database. For this task I have already installed the necessary package for ssh2 and was able to get a connection. But I don't know how to get that data. My overall goal is to have this script running as a daemon and continually retrieve information to save.

I have tried using ssh2_shell and use the returned stream resource by stream_get_contents but it returns false.

$stdio_stream = ssh2_shell($connection);
$contents = get_resource_type ($stdio_stream);
echo $contents;
$contents = stream_get_contents ($stdio_stream);
if ($contents) {
    print_r($contents); 
} else {
    echo 'it failed';
}

And I have tried this as per User Contributed Notes

$stdout_stream = ssh2_exec($connection, "/bin/ls -la /tmp");
$dio_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDIO);
$result_dio = stream_get_contents($dio_stream);
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
jerrmhs
  • 33
  • 5

1 Answers1

0

Figured it out! The trick is timing. The Shell has to have data on it in order to read. Most of the time using a shell you are sending commands and then reading data from said command, but in my case the server is just spitting data out, so i have to put sleep(1) to fill the buffer.

Here is what i got to work for a shell connection that is always sending data.

$sshConn=ssh2_connect($ipAddress, 22);
usleep(500);

ssh2_auth_password($sshConn,$userName,$password);
$shell = ssh2_shell($sshConn);
#   Here we are waiting for Shell to initialize
#   Increase this a bit if you get unexpected results
usleep(9000);
$count = 0;
while($count<3) { //run ten times
    sleep(1);
    while(($line = fgets($shell))) {
        echo "$line</br>";
    }
    $count++;
}

See PHP Programming/SSH Class for more information.

jerrmhs
  • 33
  • 5