I am connecting to an ssh server and using ssh2_shell
to create an interactive bash
shell.
The problem I have is how to send a command to the shell and get the response for the command accurately.
This is what I am currently doing:
$stream = ssh2_connect();
$shell = ssh2_shell($stream, 'bash');
fwrite($shell, "whoami\n");
fwrite(STDOUT, fread($shell, 2048) . PHP_EOL);
The problem with the above code is the output to STDOUT
(for commandline view) shows something like Last login to server etc..
aka the welcome message. I have to wait a second or two and then read from the shell again to get the output of the command I sent.
Now I can solve this by doing sleep(1)
after any command I send but this is very hacky. If the command takes longer than a second, I will not get the results. If the command takes less than a second, I waste time.
I tried stream_set_blocking($shell, true)
before writing the command and calling fread
but the problem still persists unless I sleep after the command.
Basically, how can I use ssh2_shell, send a command and get the response for that command regardless of how long it will take, without timing out the script by requesting content of a blocked stream after the shell has returned its contents?