Josh
Josh

Reputation: 83

Phpseclib ssh2 read from stream only when data is available, otherwise write available data

I'm using phpseclib and essentially what I'm trying to do is have write data from the exec stream into a file whenever it receives any data from the stream (rather than wait for the data to show up and hang in the mean time like if I were using fgets) so that I can write data to the stream that needs to be written, all within a while loop.

Pseudo code:

while stream isn't null:

    check for incoming data from the stream, if there is none, then continue to the next part of loop
        if there is data, then write it to file x.txt

    write any data into the socket that needs to be written.

How would I go about implementing this? I've tried several ways but none of them seem to work.

Upvotes: 1

Views: 1203

Answers (2)

user1013573
user1013573

Reputation: 63

or do something like ...

$tmp = $cn->exec($cmd, false);
$cn->setTimeout(10);
while (<some conditional>) {
  $tmp = $cn->_get_channel_packet(NET_SSH2_CHANNEL_EXEC);
  switch (true) {
    case === true:
      # Completed (or timed out if you are using setTimeout)
      if ($cn->is_timeout) {
        # Timed out
        break;  # Go through loop again?
      }
      break 2;
    case === false:
      # Disconnect or error
      break 2;
    default:
      # write to your file
      break;
  }

  # Other stuff to do before going back around
}

It will pause up to 10 seconds waiting and then give control back. Depends on what you are attempting to accomplish.

Upvotes: 0

neubert
neubert

Reputation: 16802

It seems like the $callback parameter of Net_SSH2::exec() might do what you're wanting. eg.

function packet_handler($str)
{
    global $fp;
    fputs($fp, $str);
}

$ssh->exec('ping 127.0.0.1', 'packet_handler');
?>

Failing that... maybe you could do something like this (untested):

$ssh->setTimeout(.1);
$ssh->exec('command');
while ($ssh->isConnected()) {
    if (stream_select(...)) {
        fputs($fp, $ssh->read());
    }
    $ssh->write(...);
}

You'll probably need a PTY as well.

Upvotes: 1

Related Questions