Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Secure Shell2 Functions : ssh2_exec

ssh2_exec

Execute a command on a remote server (PECL ssh2:0.10-0.9)
resource ssh2_exec ( resource session, string command [, string pty [, array env [, int width [, int height [, int width_height_type]]]]] )

Example 2348. Executing a command

<?php
$connection
= ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_exec($connection, '/usr/local/bin/php -i');
?>

Code Examples / Notes » ssh2_exec

tabber dot watts

This is the best way I found to automatically run multiple commands or commands that might take longer then expected.  NOTE: this assumes that no where in the output is there the text '[end]' otherwise the function will end prematurely.  Hope this helps people.
<?php
$ip = 'ip_address';
$user = 'username';
$pass = 'password';
$connection = ssh2_connection($ip);
ssh2_auth_password($connection,$user,$pass);
$shell = ssh2_shell($connection,"bash");
//Trick is in the start and end echos which can be executed in both *nix and windows systems.
//Do add 'cmd /C' to the start of $cmd if on a windows system.
$cmd = "echo '[start]';your commands here;echo '[end]'";
$output = user_exec($shell,$cmd);
fclose($shell);
function user_exec($shell,$cmd) {
 fwrite($shell,$cmd . "\n");
 $output = "";
 $start = false;
 $start_time = time();
 $max_time = 2; //time in seconds
 while(((time()-$start_time) < $max_time)) {
   $line = fgets($shell);
   if(!strstr($line,$cmd)) {
     if(preg_match('/\[start\]/',$line)) {
       $start = true;
     }elseif(preg_match('/\[end\]/',$line)) {
       return $output;
     }elseif($start){
       $output[] = $line;
     }
   }
 }
}
?>


jon-eirik pettersen

The command  may not finish before the function return if the stream is not set to blocking mode. You may have to set the stream to blocking mode in order to get any output from the command.
<?php
 // [Open connection]
 // ...
 $stream = ssh2_exec($connection, 'ps ax');
 stream_set_blocking($stream, true);
 
 // The command may not finish properly if the stream is not read to end
 $output = stream_get_contents($stream);
 
 // ...
 // [Close stream and connection]
?>


betsy gamrat

It is also good to use register_shutdown_function to shred the keys after this runs.

yairl

If you want to run many exec orders throught ssh2 in the same process using the same variable $stream for exemple and to read the output for each order, you must close the stream after each order else you will not be able to read the next order output.
$stream=ssh2_exec($conn_id,"/usr/bin/ls .");
   stream_set_blocking( $stream, true );
   $cmd=fread($stream,4096);
fclose($stream);
if(ereg("public_html",$cmd)){
...........................................
}
$stream=ssh2_exec($conn_id,"/usr/bin/ls public_html");
   stream_set_blocking( $stream, true );
   $cmd=fread($stream,4096);
fclose($stream);
if(ereg("images",$cmd)){
..........................................
}

$stream=ssh2_exec($conn_id,"/usr/bin/ls public_html/images");
   stream_set_blocking( $stream, true );
   $cmd=fread($stream,4096);
fclose($stream);
if(ereg("blabla",$cmd)){
..........................................
}


betsy gamrat

If the ssh2_exec takes awhile to run, and you need a handshake, you can use a file.  In this case, $flag names a handshake file that is written when the ssh script finishes.
               $stream = ssh2_exec($connection, $command . " $public_key $private_key;");
               $i=0;
               while (!file_exists ($flag) && ($i < MAX_TIME))
               {
                       sleep(1);
                       $i++;
               }
               $ret_val=($stream!=FALSE);
This is an extract out of the bash script that is running.  Be sure to allow the webserver permission to read the file that the script writes.
echo 0 > $OUTFILE
chmod 666 $OUTFILE
One other note:  you can put more than one command in by separating them with ';' (semicolons).


gakksimian

Executing remote Windows commands...
After some hair pulling, I thought I'd suggest a couple things that might help others:
1. Use 'ssh2_fetch_stream' to open a stderr stream according to the manual.
2. Windows shell commands require 'cmd /C [command]' to execute.  (I had forgotten this)
<?php
   // code fragment
   $stdout_stream = ssh2_exec($connection, 'cmd /C dir');
   $stderr_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDERR);
?>
I didn't realize the need for the 'cmd /C' until I saw the stderr response 'dir: not found'.


col

as of 0.9 and above, if not allocating a pty, add FALSE to the call...
old way:
ssh2_exec($connection, $command);
new way:
ssh2_exec($connection, $command, FALSE);


Change Language


Follow Navioo On Twitter
ssh2_auth_hostbased_file
ssh2_auth_none
ssh2_auth_password
ssh2_auth_pubkey_file
ssh2_connect
ssh2_exec
ssh2_fetch_stream
ssh2_fingerprint
ssh2_methods_negotiated
ssh2_publickey_add
ssh2_publickey_init
ssh2_publickey_list
ssh2_publickey_remove
ssh2_scp_recv
ssh2_scp_send
ssh2_sftp_lstat
ssh2_sftp_mkdir
ssh2_sftp_readlink
ssh2_sftp_realpath
ssh2_sftp_rename
ssh2_sftp_rmdir
ssh2_sftp_stat
ssh2_sftp_symlink
ssh2_sftp_unlink
ssh2_sftp
ssh2_shell
ssh2_tunnel
eXTReMe Tracker