diff --git a/src/SSHConnection.php b/src/SSHConnection.php index d056b3d..1019f75 100644 --- a/src/SSHConnection.php +++ b/src/SSHConnection.php @@ -18,6 +18,7 @@ class SSHConnection private $username; private $password; private $privateKeyPath; + private $privateKeyContents; private $timeout; private $connected = false; private $ssh; @@ -52,6 +53,12 @@ public function withPrivateKey(string $privateKeyPath): self return $this; } + public function withPrivateKeyString(string $privateKeyContents): self + { + $this->privateKeyContents = $privateKeyContents; + return $this; + } + public function timeout(int $timeout): self { $this->timeout = $timeout; @@ -68,8 +75,8 @@ private function sanityCheck() throw new InvalidArgumentException('Username not specified.'); } - if (!$this->password && (!$this->privateKeyPath)) { - throw new InvalidArgumentException('No password or private key path specified.'); + if (!$this->password && !$this->privateKeyPath && !$this->privateKeyContents) { + throw new InvalidArgumentException('No password or private key specified.'); } } @@ -83,9 +90,15 @@ public function connect(): self throw new RuntimeException('Error connecting to server.'); } - if ($this->privateKeyPath) { + if ($this->privateKeyPath || $this->privateKeyContents) { $key = new RSA(); - $key->loadKey(file_get_contents($this->privateKeyPath)); + + if ($this->privateKeyPath) { + $key->loadKey(file_get_contents($this->privateKeyPath)); + } else if ($this->privateKeyContents) { + $key->loadKey($this->privateKeyContents); + } + $authenticated = $this->ssh->login($this->username, $key); if (!$authenticated) { throw new RuntimeException('Error authenticating with public-private key pair.'); diff --git a/tests/Integration/SSHConnectionTest.php b/tests/Integration/SSHConnectionTest.php index 1ec94ba..e194ed4 100644 --- a/tests/Integration/SSHConnectionTest.php +++ b/tests/Integration/SSHConnectionTest.php @@ -55,6 +55,26 @@ public function testSSHConnectionWithKeyPair() $this->assertEquals('', $command->getRawError()); } + public function testSSHConnectionWithKeyContents() + { + $privateKeyContents = file_get_contents('/home/travis/.ssh/id_rsa'); + + $connection = (new SSHConnection()) + ->to('localhost') + ->onPort(22) + ->as('travis') + ->withPrivateKeyString($privateKeyContents) + ->connect(); + + $command = $connection->run('echo "Hello world!"'); + + $this->assertEquals('Hello world!', $command->getOutput()); + $this->assertEquals('Hello world!'."\n", $command->getRawOutput()); + + $this->assertEquals('', $command->getError()); + $this->assertEquals('', $command->getRawError()); + } + public function testSSHConnectionWithPassword() { $connection = (new SSHConnection())