Reputation: 509
I'm using SSH2 to establish a stream into a device running modified linux. After the stream is established, I set blocking to true and begin reading the output. Once I see the word "Last", I know that the system is ready to accept commands, so I send one. I then read the output generated by that command.
This all works perfectly, except, I have to manually close the stream. I'm pretty sure that I'm not getting an EOF or newline back and this is probably why, however, this is all new to me so I could be wrong.
Looking to exit once the output is done.
Here is what I'm looking for before I send the first command:
Last login: Tue May 7 06:41:55 PDT 2013 from 10.150.102.115
The loop that echos the output. I have to check for the word "Last" - I ignore if it its seen more than once. (It was causing the loop to repeat.):
// Prevents premature termination
$lastCount = 1;
stream_set_blocking($stdio, true);
while($line = fgets($stdio)) {
$count++;
flush();
if (strstr($line, 'Last') && $lastCount == 1) {
fwrite($stdio,$command . PHP_EOL);
$lastCount--;
}
echo $line;
}
fclose($stdio);
Upvotes: 1
Views: 5617
Reputation: 21
Your mode is incorrect and should be set to 0.
If mode is 0, the given stream will be switched to non-blocking mode, and if 1, it will be switched to blocking mode. This affects calls like fgets() and fread() that read from the stream. In non-blocking mode an fgets() call will always return right away while in blocking mode it will wait for data to become available on the stream.
http://php.net/manual/en/function.stream-set-blocking.php
Upvotes: 2
Reputation: 124
Looks like there is a trick to using blocking: http://www.php.net/manual/en/function.stream-set-blocking.php#110755
Upvotes: 0