Last active
August 29, 2015 14:24
-
-
Save gcphost/fe9f02696dfc06c44faa to your computer and use it in GitHub Desktop.
PHP SSH2 Wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class SSH{ | |
var $host=''; | |
var $port=''; | |
var $user=''; | |
var $pass=''; | |
var $connection=''; | |
var $sudo=''; | |
var $authed=false; | |
var $privkey=false; | |
var $pubkey=false; | |
var $passphrase=false; | |
var $connect_rsa=false; | |
public function __construct($host, $port, $user, $pass=false, $pubkey=false, $privkey=false, $passphrase=false){ | |
$this->host=$host; | |
$this->port=$port; | |
$this->user=$user; | |
$this->pass=$pass; | |
if($privkey && $pubkey){ | |
$this->privkey=$privkey; | |
$this->pubkey=$pubkey; | |
if($passphrase) $this->passphrase=$passphrase; | |
$this->connect_rsa = array('hostkey'=>'ssh-rsa'); | |
} else if($user != 'root') $this->sudo="echo '$pass' | sudo -S "; | |
$this->Connect(); | |
$this->Auth(); | |
} | |
public function __destruct(){ | |
$this->Execute('exit'); | |
} | |
public function Connect(){ | |
$this->connection = ssh2_connect($this->host, $this->port, $this->connect_rsa); | |
} | |
public function Auth(){ | |
if(!$this->connection) return false; | |
$this->authed = $this->connect_rsa != false | |
? ssh2_auth_pubkey_file($this->connection, $this->user, $this->pubkey, $this->privkey, $this->passphrase) | |
: ssh2_auth_password($this->connection, $this->user, $this->pass); | |
} | |
public function Execute($command, $return=false){ | |
if(!$this->authed) return false; | |
$stream=ssh2_exec($this->connection, $this->sudo.$command); | |
stream_set_blocking( $stream, true ); | |
if($return) $cmd = fread($stream, 8096); | |
fclose($stream); | |
if($return) return trim($cmd); | |
} | |
public function Screen($command, $screen){ | |
$screenlog="/root/.screenrc.watch$screen"; | |
$screencontent= "logfile /root/screenwatch$screen.log\nlog on"; | |
$this->Execute("printf '$screencontent' > $screenlog", true); | |
return $this->Execute("screen -c $screenlog -mdLS screenwatch$screen bash -c \"$command\"", true); | |
} | |
public function Watch($screen){ | |
$screenStatus=$this->Execute("screen -wipe > /dev/null ; screen -list | grep screenwatch$screen | awk -F . '{ print $1 }' | sed -e s/.//", true); | |
$screenLog=$this->Execute("cat ~/screenwatch$screen.log", true); | |
return array((int) $screenStatus, $screenLog); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment