Weave Code
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

Ssh Bundle Laravel Package

devlabs91/ssh-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run:

    composer require devlabs91/ssh-bundle
    

    (Note: The README mentions spaceheadlabs/ssh-bundle, but the package name in the prompt is devlabs91/ssh-bundle. Verify the correct package name in your project.)

  2. Enable the Bundle Add to config/bundles.php (Laravel 5.5+):

    return [
        // ...
        Devlabs91\SshBundle\SshBundle::class,
    ];
    
  3. First Use Case Configure SSH connections in config/ssh.php (auto-generated after installation). Example:

    return [
        'connections' => [
            'production' => [
                'host' => 'your-server.com',
                'username' => 'deploy',
                'password' => env('SSH_PASSWORD'), // Use Laravel env()
                'port' => 22,
            ],
        ],
    ];
    
  4. Basic Usage Inject the SshManager service and execute commands:

    use Devlabs91\SshBundle\Manager\SshManager;
    
    public function __construct(SshManager $sshManager) {
        $this->sshManager = $sshManager;
    }
    
    public function deploy() {
        $result = $this->sshManager->execute('production', 'ls -la');
        dd($result); // Output: ['stdout' => "...", 'stderr' => "...", 'exitCode' => 0]
    }
    

Implementation Patterns

Core Workflows

  1. Command Execution Use execute() for one-off commands:

    $this->sshManager->execute('connection_name', 'cd /path && ./script.sh');
    
  2. SFTP File Operations Leverage the SftpManager (if available) for file transfers:

    $this->sftpManager->put('local/path', 'remote/path', 'connection_name');
    $this->sftpManager->get('remote/path', 'local/path', 'connection_name');
    
  3. Artisan Command Integration Create a custom Artisan command to wrap SSH logic:

    use Devlabs91\SshBundle\Manager\SshManager;
    use Illuminate\Console\Command;
    
    class SshDeployCommand extends Command {
        protected $sshManager;
    
        public function __construct(SshManager $sshManager) {
            parent::__construct();
            $this->sshManager = $sshManager;
        }
    
        public function handle() {
            $this->sshManager->execute('production', 'git pull origin main');
        }
    }
    
  4. Environment-Specific Connections Dynamically switch connections based on Laravel’s environment:

    $connection = config("ssh.connections.{$this->app->environment()}");
    $this->sshManager->execute($connection, '...');
    
  5. Parallel Executions Use Laravel’s queues to run SSH tasks asynchronously:

    Dispatch(new SshJob($this->sshManager, 'backup', 'tar -czf backup.tar.gz /data'));
    

Integration Tips

  1. Laravel Env Integration Store sensitive credentials in .env:

    SSH_PASSWORD=your_password
    SSH_PRIVATE_KEY=~/.ssh/id_rsa
    

    Reference them in config/ssh.php:

    'password' => env('SSH_PASSWORD'),
    'private_key' => env('SSH_PRIVATE_KEY'),
    
  2. Event Listeners Trigger SSH actions on model events (e.g., after saving a file):

    public function handle(FileUploaded $event) {
        $this->sshManager->execute('ftp', "mv /tmp/{$event->file->hash} /public/{$event->file->path}");
    }
    
  3. Service Providers Extend the bundle’s functionality by binding additional managers:

    public function register() {
        $this->app->bind('custom.ssh', function ($app) {
            return new CustomSshManager($app['ssh.manager']);
        });
    }
    
  4. Logging Log SSH output for debugging:

    $result = $this->sshManager->execute('connection', 'command', [
        'log' => true, // Logs to Laravel's log channel
    ]);
    

Gotchas and Tips

Pitfalls

  1. Connection Timeouts

    • Issue: SSH commands may hang due to network issues or server timeouts.
    • Fix: Configure timeouts in config/ssh.php:
      'timeout' => 30, // Seconds
      
    • Debug: Use stderr in the result to diagnose failures:
      if ($result['exitCode'] !== 0) {
          Log::error("SSH Error: " . $result['stderr']);
      }
      
  2. Key-Based Authentication

    • Issue: Password authentication may fail if the server only allows keys.
    • Fix: Configure private keys in config/ssh.php:
      'private_key' => storage_path('app/ssh/id_rsa'),
      'passphrase' => env('SSH_KEY_PASSPHRASE'),
      
    • Note: Ensure the key has the correct permissions (chmod 600).
  3. Laravel vs. Symfony

    • Issue: The bundle is originally for Symfony 3, which may cause compatibility issues.
    • Fix:
      • Check for Laravel-specific adapters or forks (e.g., devlabs91/ssh-bundle).
      • Override the bundle’s service provider if needed:
        // app/Providers/SshServiceProvider.php
        public function register() {
            $this->app->bind(\Spacehead\SshBundle\Manager\SshManager::class, function ($app) {
                return new LaravelSshManagerAdapter($app['config']['ssh']);
            });
        }
        
  4. Command Output Buffering

    • Issue: Large outputs may not display fully or may time out.
    • Fix: Stream output for large commands:
      $this->sshManager->execute('connection', 'tail -f /var/log/large.log', [
          'stream' => true,
      ]);
      
  5. Dependency Conflicts

    • Issue: The bundle may pull in old versions of phpseclib or symfony/process.
    • Fix: Pin versions in composer.json:
      "require": {
          "phpseclib/phpseclib": "^3.0",
          "symfony/process": "^5.0"
      }
      

Debugging Tips

  1. Enable Verbose Output Pass verbose: true to see raw command execution:

    $this->sshManager->execute('connection', 'ls -la', ['verbose' => true]);
    
  2. Check SSH Agent Ensure your SSH agent is running and keys are added:

    eval $(ssh-agent -s)
    ssh-add ~/.ssh/id_rsa
    
  3. Test Locally First Use a local SSH server (e.g., ssh localhost) to test commands before deploying to production.

  4. Handle Special Characters Escape special characters in commands:

    $command = escapeshellarg('path with spaces');
    $this->sshManager->execute('connection', $command);
    

Extension Points

  1. Custom Command Builders Extend the bundle’s command builder to add pre/post hooks:

    $this->sshManager->extend(function ($builder) {
        $builder->prepend('echo "Starting command..."');
        $builder->append('echo "Command finished"');
    });
    
  2. Add SSH Connection Types Support additional protocols (e.g., SFTP, Mosh) by extending the manager:

    class ExtendedSshManager extends \Devlabs91\SshBundle\Manager\SshManager {
        public function mosh($connection, $command) {
            // Custom Mosh logic
        }
    }
    
  3. Integrate with Laravel Horizon Queue SSH jobs for background processing:

    SshJob::dispatch('connection', 'long-running-command')->onConnection('ssh-queue');
    
  4. Add Rate Limiting Limit SSH command frequency to avoid server bans:

    $this->sshManager->execute('connection', 'command', [
        'throttle' => 60, // 1 command per minute
    ]);
    
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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui