note 112820 added to function.ssh2-connect

From: Date: Fri, 26 Jul 2013 09:20:51 +0000
Subject: note 112820 added to function.ssh2-connect
Groups: php.notes 
Request: Send a blank email to php-notes+get-195779@lists.php.net to get a copy of this message
Hi, If you are having problems with running a ssh2 session and it waits forever during the execution of stream_get_contents, it might be because the remote system has run the command and is now sitting at a # prompt waiting for the next command. I had this issue on a HP MSA box, here is the code to get around the issue. Assuming you are connected with your authentication method and $ssh contains the handle. <?php $command = "check disk"; // Open a nice large window to stop wrapping $stream = ssh2_shell ($ssh, 'xterm', null, 200, 200, SSH2_TERM_UNIT_CHARS); // Hook into the error stream $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); // Block the streams so we wait until they complete stream_set_blocking ($stream, true); stream_set_blocking($errorStream, true); // Send the commands to the terminal fwrite ($stream, $command . PHP_EOL ); // Wait give the terminal a chance to accept and start processing the command, this is a slow storage device after all sleep(2); // IMPORTANT BIT!! Send exit to the terminal to close the connection BEFORE WE WAIT FOR THE STREAM fwrite ($stream, "exit" . PHP_EOL ); sleep (2); // Print the output echo stream_get_contents($stream); $errortext=stream_get_contents($errorStream); if (strlen($errortext) > 0) { // Error Data echo "Error Data: $errortext"; exit (1); } // All Good exit (0); ?> You can't use ssh2_exec with this method (well at lease I couldn't) because on executing the first command the stream gets blocked and then you can't run the exit command, whereas a terminal seems to use one session. I hope this helps someone. ---- Server IP: 94.76.225.145 Probable Submitter: 194.9.252.225 ---- Manual Page -- http://php.net/manual/en/function.ssh2-connect.php Edit -- https://master.php.net/note/edit/112820 Del: integrated -- https://master.php.net/note/delete/112820/integrated Del: useless -- https://master.php.net/note/delete/112820/useless Del: bad code -- https://master.php.net/note/delete/112820/bad+code Del: spam -- https://master.php.net/note/delete/112820/spam Del: non-english -- https://master.php.net/note/delete/112820/non-english Del: in docs -- https://master.php.net/note/delete/112820/in+docs Del: other reasons-- https://master.php.net/note/delete/112820 Reject -- https://master.php.net/note/reject/112820 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#195779) next »