Issue
I have written a small script that issues a series of commands via write()
to a linux machine, with a 5 second sleep()
between each one. The exact same commands work when entered manually but despite being connected successfully, do not seem to work when used from a PHP script.
As this is the case, I am curious if using read()
is absolutely necessary prior to issuing a write()
command?
<?php
include('Net/SSH2.php');
$serverhostname = "IP_HERE";
$ssh_username = "root";
$ssh_password = "PASS_HERE";
// Establish new SSH2 Connection
$connection = new Net_SSH2($serverhostname, 22);
if($connection->login($ssh_username, $ssh_password))
{
echo "LOGGED IN! </br>";
sleep(5);
$result = $connection->write('en PASS_HERE\r\n');
echo "RESULT: " . $result . " </br>";
sleep(5);
$result = $connection->write('configure terminal\r\n');
echo "RESULT: " . $result . " </br>";
sleep(5);
$result = $connection->write('interface ve 110\r\n');
echo "RESULT: " . $result . " </br>";
sleep(5);
$result = $connection->write('port-name Test_Brett\r\n');
echo "RESULT: " . $result . " </br>";
}
else
{
echo "SSH Connection Failed. Check that the remote host is online and accepting connections!";
}
?>
UPDATE
$result = $connection->write('en PASS_HERE\n');
$result = $connection->write('configure terminal\n');
$result = $connection->write('interface ve 110\n');
$result = $connection->write('port-name Test_Brett\n');
$connection->setTimeout(5);
echo $connection->read();
Solution
I just did this:
$connection->write("ls -la\n");
$connection->write("pwd\n");
$connection->setTimeout(5);
echo $connection->read();
And it seemed to perform the commands just fine without a read()
between the two write()
's. But it could be that a read()
has to be done, even if just once, at the end.
What I'd do if I were you is, instead of doing sleep(5)
do $connection->setTimeout(5); $connection->read();
. You can throw away the return value of read()
. If you knew what to expect back you could just do $connection->read('pattern')
, which would be faster, but if you don't, I'd do the $connection->setTimeout(5);
route just to be on the safe side.
Answered By - neubert