PHPackages                             cesargb/ssh2-client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. cesargb/ssh2-client

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

cesargb/ssh2-client
===================

A PHP SSH2 client wrapper providing a clean and modern interface to the ssh2 extension.

0.1.0(6mo ago)00MITPHPPHP ^8.2CI passing

Since Oct 23Pushed 2mo agoCompare

[ Source](https://github.com/cesargb/php-ssh2-client)[ Packagist](https://packagist.org/packages/cesargb/ssh2-client)[ Docs](https://github.com/cesargb/php-ssh2-client)[ RSS](/packages/cesargb-ssh2-client/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (3)Versions (2)Used By (0)

PHP SSH2 Client
===============

[](#php-ssh2-client)

A PHP SSH2 client wrapper providing a clean and modern interface to the ssh2 extension.

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Basic Usage](#basic-usage)
- [Authentication Methods](#authentication-methods)
    - [Password Authentication](#password-authentication)
    - [Public Key Authentication](#public-key-authentication-with-passphrase)
    - [Agent-Based Authentication](#agent-based-authentication)
- [Executing Commands](#executing-commands)
    - [Basic Command Execution](#basic-command-execution)
    - [Exception Handling with throw()](#exception-handling-with-throw)
- [SCP File Transfers](#scp-file-transfers)
    - [Uploading Files](#uploading-a-file)
    - [Downloading Files](#downloading-a-file)
- [Testing](#testing)

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require cesargb/ssh2-client
```

**Requirements:**

- PHP 8.2 or higher
- PHP SSH2 extension (`ext-ssh2`)

Basic Usage
-----------

[](#basic-usage)

```
require 'vendor/autoload.php';

use Cesargb\Ssh\Ssh2Client;

// Connect to the SSH server
$sshClient = Ssh2Client::connect(host: 'localhost');

// Get server fingerprint
$fingerprint = $sshClient->fingerPrint();
echo "Server Fingerprint: {$fingerprint}\n";

// Authenticate
$sshSession = $sshClient->withAuthPassword('username', 'password');

// Execute a command
$commandResult = $sshSession->command()->execute('ls -la');

// Check the result
if (! $commandResult->succeeded()) {
    echo "Error Output: {$commandResult->errorOutput}\n";
    exit($commandResult->getExitStatus());
}

echo "Command Output: {$commandResult->output}\n";

// Disconnect when done
$sshSession->disconnect();
```

Authentication Methods
----------------------

[](#authentication-methods)

The library supports multiple authentication methods. All authentication methods return an `SshSession` object that you can use to execute commands or transfer files.

### Password Authentication

[](#password-authentication)

Authenticate using a username and password:

```
$sshClient = Ssh2Client::connect(host: 'example.com', port: 22);
$sshSession = $sshClient->withAuthPassword(
    username: 'root',
    password: 'root_password'
);
```

### Public Key Authentication with Passphrase

[](#public-key-authentication-with-passphrase)

Authenticate using SSH key pairs:

```
$sshClient = Ssh2Client::connect(host: 'example.com', port: 22);
$sshSession = $sshClient->withAuthPublicKey(
    username: 'root',
    publicKey: '/path/to/public/key.pub',
    privateKey: '/path/to/private/key',
    passphrase: 'passphrase if required'  // Optional, use empty string if no passphrase
);
```

### Agent-Based Authentication

[](#agent-based-authentication)

Authenticate using the SSH agent:

```
$sshClient = Ssh2Client::connect(host: 'example.com', port: 22);
$sshSession = $sshClient->withAuthAgent('username');
```

Executing Commands
------------------

[](#executing-commands)

### Basic Command Execution

[](#basic-command-execution)

Execute commands and check the results manually:

```
// Connect and authenticate
$sshSession = Ssh2Client::connect(host: 'example.com', port: 22)
    ->withAuthPassword('username', 'password');

// Execute a command
$result = $sshSession->command()->execute('ls -l');

// Check if the command succeeded
if ($result->succeeded()) {
    echo "Success: {$result->output}\n";
} else {
    echo "Failed: {$result->errorOutput}\n";
    echo "Exit code: {$result->getExitStatus()}\n";
}

// Disconnect when done
$sshSession->disconnect();
```

**Result properties:**

- `$result->succeeded()` - Returns `true` if the command executed successfully (exit status 0)
- `$result->getExitStatus()` - Returns the exit status code of the command (e.g., 0 for success, 127 for command not found)
- `$result->output` - Contains the command output from stdout
- `$result->errorOutput` - Contains any error output from stderr
- `$result->command` - The command that was executed

### Exception Handling with throw()

[](#exception-handling-with-throw)

For cleaner error handling, you can use the `throw()` method to automatically throw exceptions when commands fail:

```
use Cesargb\Ssh\Exceptions\SshCommandException;

try {
    // Enable automatic exception throwing
    $sshSession = Ssh2Client::connect(host: 'example.com', port: 22)
        ->withAuthPassword('username', 'password')
        ->throw();  // Enable exception mode

    // Execute commands - will throw exception on failure
    $result = $sshSession->command()->execute('ls -l');
    echo "Success: {$result->output}\n";

    // This command will throw an exception if it fails
    $result = $sshSession->command()->execute('some-command');

} catch (SshCommandException $e) {
    echo "Command failed: {$e->getMessage()}\n";
    echo "Exit code: {$e->result->getExitStatus()}\n";
    echo "Error output: {$e->result->errorOutput}\n";
} finally {
    $sshSession->disconnect();
}
```

**Benefits of using `throw()`:**

- Eliminates the need for manual success checks after each command
- Provides cleaner error handling with try-catch blocks
- The exception contains the full `ExecResult` object with all command details
- Ideal for scripts where command failures should stop execution

**Note:** When using `throw()`, any command that returns a non-zero exit status will throw a `SshCommandException`.

SCP File Transfers
------------------

[](#scp-file-transfers)

Transfer files securely between local and remote systems using SCP (Secure Copy Protocol).

### Uploading a File

[](#uploading-a-file)

Upload a local file to the remote server:

```
$sshSession = Ssh2Client::connect(host: 'example.com', port: 22)
    ->withAuthPassword('username', 'password');

$scpResult = $sshSession
    ->scp()
    ->upload('/local/path/to/file.txt')
    ->to('/remote/path/to/file.txt');

if ($scpResult->succeeded()) {
    echo "File uploaded successfully.\n";
} else {
    echo "File upload failed.\n";
}

$sshSession->disconnect();
```

### Downloading a File

[](#downloading-a-file)

Download a file from the remote server to your local system:

```
$sshSession = Ssh2Client::connect(host: 'example.com', port: 22)
    ->withAuthPassword('username', 'password');

$scpResult = $sshSession
    ->scp()
    ->download('/remote/path/to/file.txt')
    ->to('/local/path/to/file.txt');

if ($scpResult->succeeded()) {
    echo "File downloaded successfully.\n";
} else {
    echo "File download failed.\n";
}

$sshSession->disconnect();
```

**Note:** SCP operations also support the `throw()` method for automatic exception handling, similar to command execution.

Testing
-------

[](#testing)

```
composer test
```

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance77

Regular maintenance activity

Popularity0

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 Bus Factor1

Top contributor holds 98.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

207d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/25681494?v=4)[Cesar Garcia](/maintainers/cesargb)[@cesargb](https://github.com/cesargb)

---

Top Contributors

[![cesargb](https://avatars.githubusercontent.com/u/25681494?v=4)](https://github.com/cesargb "cesargb (71 commits)")[![Copilot](https://avatars.githubusercontent.com/in/1143301?v=4)](https://github.com/Copilot "Copilot (1 commits)")

---

Tags

phpssh-client

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/cesargb-ssh2-client/health.svg)

```
[![Health](https://phpackages.com/badges/cesargb-ssh2-client/health.svg)](https://phpackages.com/packages/cesargb-ssh2-client)
```

###  Alternatives

[alb/oembed

oEmbed consumer library

1799.4k](/packages/alb-oembed)[jajuma/awesomehyva

This Magento 2 extension allows using Font Awesome 5 icons with Hyvä Themes

1349.1k](/packages/jajuma-awesomehyva)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
