2

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?

Ozzy
  • 10,285
  • 26
  • 94
  • 138

1 Answers1

0

What you describe is the intended behavior of ssh2_shell - it is interactive. That means you would need to work with timeouts.

If you want a command or script executed on the remote host and just receive its output you need non-interactive execution - ssh2_exec.

Zrin
  • 919
  • 15
  • 25