Hey, the start for a PEAR SSH2 package! The code is available under the GNU GPL ;-)
<?php
class SSH2
{
private $con;
private $host;
private $port;
private $login;
public function __construct($host=NULL, $port=22)
{
$this->host = $host;
$this->port = $port;
$this->con = ssh2_connect($this->host, $this->port);
// connection attempt successful ?
if($this->con === false)
{
$this->con = NULL;
throw new SSH2Exception("Could not connect to host '".$this->host."' on port ".$this->port);
}
}
public function login($login=NULL, $password=NULL)
{
if(empty($login)) {
throw new IllegalArgumentException("Login failed, no username supplied");
}
$this->login = $login;
// try to log in
if(!ssh2_auth_password($this->con, $this->login, $password))
{
$this->con = NULL;
throw new SSH2Exception("Password authentication failed for user '".$this->login."'");
}
}
// returns an array like: array('stdout goes here', 'stderr')
public function exec($cmd)
{
if(empty($this->con)) {
throw new SSH2Exception("Exec failed, no connection available");
}
// execute the command
$stdio = ssh2_exec($this->con, $cmd);
// get the error stream, otherwise this would be lost
$stderr = ssh2_fetch_stream ($stdio, SSH2_STREAM_STDERR);
// set to blocking mode or we won't get any data
stream_set_blocking($stdio, true);
$data_std = '';
$data_err = '';
// let's fetch the result of our command
while($data = fread($stdio, 131072)) {
//while($data = fgets($stdio)) {
$data_std .= $data;
}
while($data = fread($stderr, 80000)) {
$data_err .= $data;
}
// close the streams
fclose($stdio);
fclose($stderr);
return array($data_std, $data_err);
}
}
class SSH2Exception extends Exception {}
class IllegalArgumentException extends Exception {}
?>