Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Ssh Laravel Package

herzult/php-ssh

A lightweight PHP library for running SSH commands locally or remotely with a fluent API. Execute commands, capture stdout/stderr and exit codes, handle timeouts, and compose pipelines—useful for deployments, server automation, and remote task orchestration.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require herzult/php-ssh
    

    Add to composer.json if not using autoloading:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Herzult\\SSH\\": "vendor/herzult/php-ssh/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case: Connecting to a Server

    use Herzult\SSH\Connection;
    
    $connection = new Connection('[email protected]', 'password');
    $connection->connect();
    
  3. Where to Look First

    • Documentation: Check the GitHub README (if available) or source code for basic usage.
    • Source Code: Focus on src/Herzult/SSH/Connection.php for core functionality and src/Herzult/SSH/Command.php for executing commands.
    • Tests: If available, examine tests/ for real-world usage examples.

Implementation Patterns

Usage Patterns

  1. Basic Command Execution

    $connection = new Connection('[email protected]', 'password');
    $connection->connect();
    
    $output = $connection->exec('ls -la');
    echo $output;
    
  2. Handling Output and Errors

    try {
        $output = $connection->exec('ls /nonexistent');
        echo $output;
    } catch (Herzult\SSH\Exception\SSHException $e) {
        echo "Error: " . $e->getMessage();
    }
    
  3. Streaming Output for Large Files

    $connection->exec('cat largefile.log', function ($line) {
        echo $line;
    });
    
  4. SFTP File Operations

    $connection->put('local.txt', 'remote.txt');
    $connection->get('remote.txt', 'local_copy.txt');
    
  5. Reusing Connections

    $connection = new Connection('[email protected]', 'password');
    $connection->connect();
    
    // Reuse connection for multiple commands
    $connection->exec('cd /path');
    $connection->exec('pwd');
    
  6. Integration with Laravel

    • Service Provider: Register the SSH client as a singleton.
      // app/Providers/AppServiceProvider.php
      public function register()
      {
          $this->app->singleton('ssh', function () {
              return new Herzult\SSH\Connection(config('ssh.host'), config('ssh.password'));
          });
      }
      
    • Config File: Store credentials in config/ssh.php.
      return [
          'host' => '[email protected]',
          'password' => env('SSH_PASSWORD'),
      ];
      
    • Facade: Create a facade for cleaner syntax.
      // app/Facades/SSH.php
      namespace App\Facades;
      
      use Illuminate\Support\Facades\Facade;
      
      class SSH extends Facade {
          protected static function getFacadeAccessor() { return 'ssh'; }
      }
      
      Usage:
      SSH::exec('ls -la');
      
  7. Parallel SSH Commands Use PHP’s parallel package or pthreads to run multiple SSH commands concurrently (if supported by the server).


Workflows

  1. Automated Deployments

    • Use SSH to pull code, run migrations, and restart services.
    $connection->exec('git pull origin main');
    $connection->exec('php artisan migrate');
    $connection->exec('sudo service nginx restart');
    
  2. Log Aggregation

    • Fetch logs from multiple servers and store them locally.
    $servers = ['[email protected]', '[email protected]'];
    foreach ($servers as $server) {
        $connection = new Connection($server, 'password');
        $connection->exec('tail -n 100 /var/log/app.log', function ($line) {
            Log::info($line);
        });
    }
    
  3. Server Monitoring

    • Check server status and send alerts.
    $output = $connection->exec('df -h');
    if (strpos($output, '90%') !== false) {
        Alert::send('Disk space low on server!');
    }
    
  4. Dynamic Command Building

    • Construct commands based on Laravel input or config.
    $command = "docker-compose up " . ($debug ? "-d" : "");
    $connection->exec($command);
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package

    • Last release in 2015 means it may not support modern PHP versions (7.4+). Test thoroughly or fork and update.
    • No active maintenance; use at your own risk for production.
  2. No Native SSH Key Support

    • Only password authentication is supported. For key-based auth, extend the Connection class or use a wrapper like phpseclib.
  3. Limited Error Handling

    • Custom exceptions (SSHException) may not cover all edge cases. Wrap calls in try-catch blocks.
  4. Blocking Operations

    • exec() is synchronous. For long-running commands, use streaming or run in a queue (e.g., Laravel Queues).
  5. No Built-in Retry Logic

    • Network issues may cause failures. Implement retry logic manually:
      $attempts = 0;
      while ($attempts < 3) {
          try {
              $connection->exec('command');
              break;
          } catch (\Exception $e) {
              $attempts++;
              sleep(2);
          }
      }
      
  6. Resource Leaks

    • Always call $connection->disconnect() after use to free resources.
    • Use __destruct() or a context manager (e.g., Laravel’s illuminate/support/Manager) to ensure cleanup.

Debugging

  1. Enable Verbose Output

    • Extend the Connection class to log raw SSH traffic:
      class DebugConnection extends Herzult\SSH\Connection {
          public function exec($command) {
              error_log("Executing: $command");
              return parent::exec($command);
          }
      }
      
  2. Check Underlying PHP SSH Functions

    • The package likely uses ssh2_connect(), ssh2_exec(), etc. Debug these functions directly if issues arise.
  3. Test Locally First

    • Use a local SSH server (e.g., Docker with linuxserver/openssh-server) to test commands before deploying to production.

Tips

  1. Extend for Custom Features

    • Add methods for common tasks (e.g., restartService(), checkDiskSpace()):
      class CustomSSH extends Herzult\SSH\Connection {
          public function restartNginx() {
              $this->exec('sudo service nginx restart');
          }
      }
      
  2. Use Laravel’s Cache for Connections

    • Cache connections to avoid repeated authentication:
      $connection = Cache::remember('ssh_connection', 3600, function () {
          return new Connection('[email protected]', 'password');
      });
      
  3. Combine with Other Packages

    • Use phpseclib for advanced SSH features (e.g., SFTP, key auth) and herzult/php-ssh for simplicity where it works.
  4. Environment-Specific Config

    • Use Laravel’s .env for credentials:
      [email protected]
      SSH_PASSWORD=securepassword
      
    • Load in config/ssh.php:
      'host' => env('SSH_HOST'),
      'password' => env('SSH_PASSWORD'),
      
  5. Queue Long-Running Tasks

    • Offload heavy SSH operations to Laravel Queues:
      SSH::dispatch(new ProcessCommand('[email protected]', 'long-running-command'));
      
      Define a job:
      class ProcessCommand implements ShouldQueue {
          protected $server;
          protected $command;
      
          public function handle() {
              $connection = new Connection($this->server, 'password');
              $connection->exec($this->command);
          }
      }
      
  6. Mock for Testing

    • Use Laravel’s Mockery to test SSH interactions without real connections:
      $mock = Mockery::mock(Herzult\SSH\Connection::class);
      $mock->shouldReceive('exec')->andReturn('mocked output');
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc
animalyoung/laravel-influxdb
onix-solutions/sms-telera
lonely-lights/prosetta
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log