Skip to content

Instantly share code, notes, and snippets.

@lifeofguenter
Created November 19, 2014 10:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lifeofguenter/fc1b75036576b1c64aed to your computer and use it in GitHub Desktop.
Save lifeofguenter/fc1b75036576b1c64aed to your computer and use it in GitHub Desktop.
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
define('SSH_HOST', '');
define('SSH_PORT', 666);
define('SSH_USER', '');
define('SSH_PASS', '');
define('REMOTE_PATH', '/var/www/');
define('REPOSITORY', 'git@gitar.io:gg/foo.git');
$ssh_client = new SSH2Client(SSH_HOST, SSH_PORT);
$ssh_client->auth(SSH_USER, SSH_PASS);
$ssh_client->connect();
if (!empty($_SERVER['argv'][1]) && $_SERVER['argv'][1] === 'init') {
echo $ssh_client->exec(sprintf('git clone %s %s', REPOSITORY, REMOTE_PATH));
} else {
echo $ssh_client->exec(sprintf('cd %s && git pull 2>&1', REMOTE_PATH));
}
$ssh_client->close();
unset($ssh_client);
class SSH2Client
{
protected $connection;
protected $host;
protected $port;
protected $user;
protected $password;
public function __construct($host, $port = 22)
{
$this->host = $host;
$this->port = (int) $port;
}
public function __destruct()
{
if (is_resource($this->connection)) {
$this->close();
}
}
public function connect()
{
if (!$this->connection = ssh2_connect($this->host, $this->port)) {
throw new Exception(sprintf('Cannot connect to server: %s', $this->host));
}
if (!ssh2_auth_password($this->connection, $this->user, $this->password)) {
throw new Exception('Authentication Failed');
}
}
public function close()
{
$this->exec('echo "EXITING" && exit;');
$this->connection = null;
}
public function auth($user, $password = null)
{
$this->user = $user;
$this->password = $password;
return $this;
}
public function exec($cmd, $pty = null, array $env = array(), $width = 80, $height = 25, $width_height_type = SSH2_TERM_UNIT_CHARS)
{
$stdout = ssh2_exec($this->connection, $cmd, $pty, $env, $width, $height, $width_height_type);
$stderr = ssh2_fetch_stream($stdout, SSH2_STREAM_STDERR);
stream_set_blocking($stderr, true);
stream_set_blocking($stdout, true);
$error = stream_get_contents($stderr);
if ($error !== '') {
throw new RuntimeException($error);
}
return stream_get_contents($stdout);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment