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.)
Enable the Bundle
Add to config/bundles.php (Laravel 5.5+):
return [
// ...
Devlabs91\SshBundle\SshBundle::class,
];
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,
],
],
];
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]
}
Command Execution
Use execute() for one-off commands:
$this->sshManager->execute('connection_name', 'cd /path && ./script.sh');
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');
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');
}
}
Environment-Specific Connections Dynamically switch connections based on Laravel’s environment:
$connection = config("ssh.connections.{$this->app->environment()}");
$this->sshManager->execute($connection, '...');
Parallel Executions Use Laravel’s queues to run SSH tasks asynchronously:
Dispatch(new SshJob($this->sshManager, 'backup', 'tar -czf backup.tar.gz /data'));
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'),
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}");
}
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']);
});
}
Logging Log SSH output for debugging:
$result = $this->sshManager->execute('connection', 'command', [
'log' => true, // Logs to Laravel's log channel
]);
Connection Timeouts
config/ssh.php:
'timeout' => 30, // Seconds
stderr in the result to diagnose failures:
if ($result['exitCode'] !== 0) {
Log::error("SSH Error: " . $result['stderr']);
}
Key-Based Authentication
config/ssh.php:
'private_key' => storage_path('app/ssh/id_rsa'),
'passphrase' => env('SSH_KEY_PASSPHRASE'),
chmod 600).Laravel vs. Symfony
devlabs91/ssh-bundle).// app/Providers/SshServiceProvider.php
public function register() {
$this->app->bind(\Spacehead\SshBundle\Manager\SshManager::class, function ($app) {
return new LaravelSshManagerAdapter($app['config']['ssh']);
});
}
Command Output Buffering
$this->sshManager->execute('connection', 'tail -f /var/log/large.log', [
'stream' => true,
]);
Dependency Conflicts
phpseclib or symfony/process.composer.json:
"require": {
"phpseclib/phpseclib": "^3.0",
"symfony/process": "^5.0"
}
Enable Verbose Output
Pass verbose: true to see raw command execution:
$this->sshManager->execute('connection', 'ls -la', ['verbose' => true]);
Check SSH Agent Ensure your SSH agent is running and keys are added:
eval $(ssh-agent -s)
ssh-add ~/.ssh/id_rsa
Test Locally First
Use a local SSH server (e.g., ssh localhost) to test commands before deploying to production.
Handle Special Characters Escape special characters in commands:
$command = escapeshellarg('path with spaces');
$this->sshManager->execute('connection', $command);
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"');
});
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
}
}
Integrate with Laravel Horizon Queue SSH jobs for background processing:
SshJob::dispatch('connection', 'long-running-command')->onConnection('ssh-queue');
Add Rate Limiting Limit SSH command frequency to avoid server bans:
$this->sshManager->execute('connection', 'command', [
'throttle' => 60, // 1 command per minute
]);
How can I help you explore Laravel packages today?