I have to connect to a server via ssh, but to access it I need to first connect to another ssh server. I use standard password access to them.
So my steps are:
ssh [email protected]
then when connected in serverdomain1 I do in terminal:
ssh [email protected]
in php, I tried to use ssh2_exec('ssh serverdomain2.com'); but no results. Then I tried also ss2_tunnel($connection, ...). but nothing worked.
This doesn't work:
$ssh = ssh2_connect('serverdomain1.com', 22);
if (ssh2_auth_password($ssh, $user,$pass)) {
$stream = ssh_exec($ssh, "ssh serverdomain2.com");
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo stream_get_contents($stream_out); // <== doesn't work!!!
}
This also doesn't work:
$ssh = ssh2_connect('serverdomain1.com', 22);
if (ssh2_auth_password($ssh, $user,$pass)) {
$tunnel = ssh2_tunnel($ssh, 'serverdomain2.com', 22);
if (!$tunnel) {
echo('no tunnel<br/>');
}
else {
fwrite($tunnel, "echo 1\n");
while (!feof($tunnel)) {
echo fgets($tunnel, 128);
}
}
}
The echo result for tunnel: "SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2.4 Protocol mismatch."
How can I do that with SSH2 from PHP?
I recently published a project that allows PHP to obtain and interact with a real Bash shell, through SSH if needed. Get it here: https://github.com/merlinthemagic/MTS
The project lets you keep bouncing from server to server using ssh.
After downloading you would simply use the following code:
//first you get a shell on the first server:
$shellObj = \MTS\Factories::getDevices()->getRemoteHost('ip_address1')->setConnectionDetail('username1', 'password1')->getShell();
//then build on that first shell, the following way.
\MTS\Factories::getDevices()->getRemoteHost('ip_address2')->setConnectionDetail('username2', 'password2')->getShell($shellObj);
//any command executed on the shell will run only on the second host you connected to.
$return1 = $shellObj->exeCmd("hostname");
echo $return1;//hostname of the second host you connected to
//
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With