Ho cercato di get ssh2_exec
per l'esecuzione e restituire la risposta dall'host remoto, ma non riesco a capire il modo corretto per farlo. Ho unito questa function in base a ciò che altri hanno raccomandato, ma la function si blocca sempre una volta che arriva a stream_get_contents($errorStream);
.
Il command che sto eseguendo è ls -l
quindi dovrebbe essere eseguito molto rapidamente.
public function exec($command) { $stream = ssh2_exec($this->ssh, $command); if (! $stream) { throw new exception('Could not open shell exec stream'); } $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); stream_set_blocking($errorStream, true); stream_set_blocking($stream, true); $err = stream_get_contents($errorStream); $response = stream_get_contents($stream); @fclose($errorStream); @fclose($stream); if ($err) { throw new exception($err); } return $response; }
Ho scoperto che la function ssh2_exec () si bloccherà se la dimensione dell'output del command raggiunge 64 KB (esattamente quel numero sulla mia scatola di sviluppo Linux).
Un modo per evitare è usare: stream_set_timeout ()
$stream = ssh2_exec($this->ssh, $command); if (! $stream) { throw new exception('Could not open shell exec stream'); } stream_set_timeout($stream, 10);
Onestamente, userei phpseclib, una pura implementazione SSH PHP . per esempio.
<?php include('Net/SSH2.php'); $ssh = new Net_SSH2('www.domain.tld'); if (!$ssh->login('username', 'password')) { exit('Login Failed'); } echo $ssh->exec('ls -l');