Reputation: 1141
I've been trying to execute two or more commands on a remote device by using PHP's ssh2_exec command but it doesn't seem to be able to execute a command, wait for a response and execute another one.
The second command that I need to run must be in the context of the first command so it must be executed in the same shell. What I mean is something like this
FWEFW # config system admin
This command will take me into a "context". The result will be something like:
FWEFW (admin) #
From here, I'd like to run a second command that could set the password or another field of (admin)
FWEFW (admin) # set password 'abcde'
Here's what I've tried so far:
$stream = ssh2_exec($con, 'config system admin');
stream_set_blocking($stream, TRUE);
$output = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
// After this, what can I do to stay in the same shell and execute the second command after "config system admin"?
Upvotes: 1
Views: 1627
Reputation: 1141
After a lot of frustration, I've come to the following conclusion:
The ssh2_exec command is useful when you need to run a single command. In my case, I needed to run multiple commands in the same session before getting the result that I needed. In order to do so here's how I went about it:
Create an interactive shell
$shell = ssh2_shell($connection, 'xterm', NULL, 400, 400, SSH2_TERM_UNIT_CHARS)
Execute your first command
fwrite($shell, 'command 1' . PHP_EOL); // Don't forget PHP_EOL => /n
Wait for the whole stream
stream_set_blocking($shell, TRUE);
Run your second command
fwrite($shell, 'command 2' . PHP_EOL);
So on and so on. I've tested it with four commands and it worked just fine.
After you've executed all the commands you can retrieve the result by "accessing the shell"
$data = "";
$buf = NULL;
while (! feof($shell))
{
$buf = fread($shell, 4096);
$data .= $buf;
}
fclose($shell);
The data you need is now stored in the $data variable. Note that, should your shell be stuck at prompt (the case most of the time) the loop will run forever until a timeout error is thrown.
To get around that, I had to run the 'exit' command in order to exit the shell.
Upvotes: 1