ssh2 class on php
曾经写过的一个ssh2类
<?php
/**
* Ssh2 Class
*
* @author tony <zhuyh@ifeng.com>
* @package noah.module.ssh2
* @version 0.1
* $Id: ssh2.php 1914 2011-04-06 17:52:24Z zhuyinghao $
*/
class Ssh2 extends Noah_base {
protected $_connect = null;
protected $_shell = null;
protected function _afterConstruct($id)
{
$this->_connect = ssh2_connect($this->_config['host'], $this->_config['port']);
ssh2_auth_password($this->_connect, $this->_config['user'], $this->_config['password']);
if(!$this->_connect)
{
throw new Ssh2_Exception('connect ssh failures');
}
}
/**
* Execute shell
* @param $cmd
*/
public function exec($cmd)
{
$stream = ssh2_exec($this->_connect, $cmd, $this->_config['shellType']);
$stderr_stream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
$data = '';
while($line = fgets($stderr_stream))
{
$data .= $line.PHP_EOL;
}
if($data)
{
return $data;
}
else
{
stream_set_blocking($stream, true);
return stream_get_contents($stream);
}
}
/**
* Upload file
* @param $localfile
* @param $remotefile
* @param $mode
*/
public function sendFile($localfile, $remotefile, $mode)
{
if(ssh2_scp_send($this->_connect, $localfile, $remotefile, $mode))
{
return true;
}
}
/**
* Upload file
* @param $localfile
* @param $remotefile
* @param $mode
*/
public function recvFile($remotefile, $localfile)
{
if(ssh2_scp_recv($this->_connect, $remotefile, $localfile))
{
return true;
}
}
/**
* Openshell
*/
public function openShell()
{
$this->_shell = ssh2_shell($this->_connect, $this->_config['shellType']);
if($this->_shell)
{
return true;
}
else
{
return false;
}
}
public function writeShell($cmd)
{
if(fwrite($this->_shell , $cmd.PHP_EOL))
{
return true;
}
}
/**
* readshell commod
*
* @param int $size
*/
public function readShell($size = 4096)
{
$data = "";
while ($buf = fread($this->_shell, $size))
{
$data .= $buf;
}
return $data;
}
public function closeShell()
{
fclose($this->_shell);
}
}