Created
January 9, 2013 22:47
-
-
Save cpliakas/4497720 to your computer and use it in GitHub Desktop.
An SSH wrapper written in PHP useful when set as the GIT_SSH variable.
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
#!/usr/bin/env php | |
<?php | |
require_once __DIR__ . '/../vendor/autoload.php'; | |
try { | |
// Get the arguments passed through the command line. | |
$args = (!empty($_SERVER['argv'])) ? $_SERVER['argv'] : array(); | |
if (!isset($args[0])) { | |
$args[0] = $_SERVER['PHP_SELF']; | |
} | |
// Ensure that all arguments are present. | |
if (!isset($args[2])) { | |
throw new \RuntimeException($args[0] . ' requires 2 parameters.'); | |
} | |
if (!$filepath = getenv('GIT_SSH_KEY')) { | |
throw new \RuntimeException($args[0] . ' expects GIT_SSH_KEY environment variable to be set.'); | |
} | |
if (!$private_key = @file_get_contents($filepath)) { | |
throw new \RuntimeException('Unable to load private key: ' . $filepath); | |
} | |
// Allow the setting of the Git SSH port. | |
$port = getenv('GIT_SSH_PORT'); | |
if (!$port) { | |
$port = 22; | |
} | |
// Parse out the userrname and host. | |
$strpos = strpos($args[1], '@'); | |
$username = substr($args[1], 0, $strpos); | |
$host = substr($args[1], $strpos + 1); | |
// Load the private key. | |
$key = new Crypt_RSA(); | |
$key->loadKey($private_key); | |
// Authenticate. | |
$ssh = new Net_SSH2($host, $port); | |
if (!$ssh->login($username, $key)) { | |
throw new \RuntimeException('Authentication failed: ' . $ssh->getLastError()); | |
} | |
// Run the wrapper. | |
print $ssh->exec($args[2]); | |
} catch (Exception $e) { | |
// Write exception message to STDERR. | |
$fh = fopen('php://stderr','a'); | |
fwrite(STDERR, $e->getMessage() . PHP_EOL); | |
fclose($fh); | |
exit(1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment