Getting Started with Laravel as a Network Automation Platform: Easier Than Python?

Discover how Laravel simplifies network automation with built-in features, making it a more structured and scalable alternative to Python.

When it comes to network automation, many developers and network engineers default to using Python, thanks to its robust libraries like Netmiko, NAPALM, and Paramiko. Python is well-suited for scripting, but it can be a bit tricky when scaling projects, building a user-friendly interface, or managing complex workflows. This is where Laravel, the PHP-based web framework, can offer a compelling alternative.

Laravel's ease of use, extensive ecosystem, and well-organized structure make it surprisingly effective for building network automation tools. In this blog, we’ll walk through how you can get started with Laravel for network automation, and why it might be simpler than building everything from scratch with Python.

Why Laravel for Network Automation?

Laravel offers several advantages for network automation:

  1. Built-In Structure: Laravel’s MVC (Model-View-Controller) architecture organizes your code in a clear way, making it easier to maintain and scale.

  2. Web Interface: Laravel’s Blade templating engine makes it easy to create a clean web UI for your automation platform.

  3. Eloquent ORM: Managing databases and logging network operations becomes easier with Laravel’s built-in ORM (Object Relational Mapping) for working with SQL databases.

  4. Job Queues and Scheduling: Laravel makes it incredibly easy to schedule tasks and queue jobs, essential for automating recurring network operations.

  5. Third-Party Integrations: Laravel’s ecosystem is vast, with plenty of packages for SSH, APIs, and more—simplifying things you’d otherwise write custom code for in Python.

Let’s dive into a simple example of using Laravel to automate network tasks.


Step 1: Install Laravel

To start, you'll need to install Laravel. If you haven’t done that already, you can install it via Composer.

composer global require laravel/installer

After installing Laravel, create a new project:

laravel new network-automation

Once Laravel is installed, navigate into your new project directory:

cd network-automation

Step 2: Set Up SSH for Network Devices

To automate network devices, you need a way to communicate with them. In Python, you would use libraries like Netmiko, but in Laravel, we can use a package like Spatie’s SSH package to easily run SSH commands.

First, install the SSH package:

composer require spatie/ssh

Now, let's create a simple controller that can SSH into a network device and run a command.

Create a New Controller

Run the following Artisan command to generate a controller:

php artisan make:controller NetworkController

This will generate a NetworkController.php file inside app/Http/Controllers/. In this controller, we'll use the Spatie SSH package to automate some tasks.

Code Example: SSH Into a Network Device

Here's how you can SSH into a network device and fetch its configuration:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Ssh\Ssh;

class NetworkController extends Controller
{
    public function fetchConfig()
    {
        // SSH credentials
        $ssh = Ssh::create('username', '192.168.1.1')
                    ->usePrivateKey('/path/to/private_key')
                    ->execute('show running-config');

        // Check if the command was successful
        if ($ssh->wasSuccessful()) {
            $output = $ssh->getOutput();
            return view('config.show', ['config' => $output]);
        } else {
            return response('Failed to fetch config.', 500);
        }
    }
}

In this example:

  • We’re SSHing into a network device (in this case, 192.168.1.1).

  • The execute('show running-config') command retrieves the running configuration.

  • If successful, the result is passed to a Blade view to be displayed.

Create a Blade View

Let’s create a simple Blade view to show the output of the network device configuration.

Create a new file named show.blade.php in the resources/views/config/ folder.

<!-- resources/views/config/show.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Device Configuration</title>
</head>
<body>
    <h1>Device Configuration</h1>
    <pre>{{ $config }}</pre>
</body>
</html>

Now, when you navigate to the route connected to this controller method, you’ll see the configuration output in your browser.

Step 3: Define a Route for the Network Controller

Next, set up a route to trigger the controller action. Open routes/web.php and add:

use App\Http\Controllers\NetworkController;

Route::get('/fetch-config', [NetworkController::class, 'fetchConfig']);

Now, if you navigate to http://your-app-url/fetch-config, you’ll trigger the SSH command, and the device’s configuration will be displayed in the web UI.

Step 4: Automate Tasks with Laravel’s Task Scheduler

One of the biggest challenges in network automation is scheduling regular tasks, like backups or status checks. Laravel’s built-in task scheduler makes this incredibly easy.

First, let’s set up a recurring task to backup the network device’s configuration every day.

Scheduling a Task

In Laravel, scheduled tasks are defined in the app/Console/Kernel.php file. Open it up and add the following inside the schedule method:

protected function schedule(Schedule $schedule)
{
    $schedule->call(function () {
        // SSH into the network device and save the configuration
        $ssh = Ssh::create('username', '192.168.1.1')
                    ->usePrivateKey('/path/to/private_key')
                    ->execute('show running-config');

        if ($ssh->wasSuccessful()) {
            $output = $ssh->getOutput();
            \Storage::put('backups/network-config-' . now()->format('Y-m-d') . '.txt', $output);
        }
    })->daily();
}

This will SSH into the device and save the configuration to a backup file in the storage/app/backups/ directory every day. The scheduler will handle running this job in the background automatically.

Running the Scheduler

To ensure the scheduler runs, you need to add the following cron entry on your server:

* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1

This will run Laravel’s task scheduler every minute, which in turn will run the defined tasks at the correct time (e.g., daily, weekly, etc.).

Step 5: Use Laravel Queues for Bulk Operations

Network automation often requires running tasks across many devices in parallel. Laravel’s job queues are perfect for this. Let’s say we want to run a command on multiple devices simultaneously—Laravel can queue up the jobs to process them in parallel.

Create a New Job

You can create a job with Artisan:

php artisan make:job RunCommandOnDevice

In the RunCommandOnDevice job, we’ll add the logic to SSH into a device and execute a command.

<?php

namespace App\Jobs;

use Spatie\Ssh\Ssh;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class RunCommandOnDevice implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $deviceIp;
    protected $command;

    public function __construct($deviceIp, $command)
    {
        $this->deviceIp = $deviceIp;
        $this->command = $command;
    }

    public function handle()
    {
        $ssh = Ssh::create('username', $this->deviceIp)
                    ->usePrivateKey('/path/to/private_key')
                    ->execute($this->command);

        if ($ssh->wasSuccessful()) {
            // Process output or log result
            \Log::info('Command successful on ' . $this->deviceIp);
        } else {
            \Log::error('Command failed on ' . $this->deviceIp);
        }
    }
}

Now, you can queue this job for multiple devices:

phpCopy code$devices = ['192.168.1.1', '192.168.1.2', '192.168.1.3'];

foreach ($devices as $device) {
    RunCommandOnDevice::dispatch($device, 'show version');
}

Laravel will queue up these jobs, and you can process them in parallel with workers.

Running the Queue Worker

To start processing the jobs, run the queue worker with:

php artisan queue:work

This allows you to scale up and handle large-scale network automation tasks efficiently.


Conclusion

While Python has been the go-to choice for network automation, Laravel offers a more structured, scalable, and user-friendly solution, especially when building out more complex automation platforms with a UI, scheduling, and job queuing. With packages like Spatie SSH and Laravel’s built-in task scheduling, you can get a powerful network automation platform up and running much faster than starting from scratch with Python.

If you’re building automation tools for larger teams or need a simple way to manage recurring network tasks, Laravel provides an excellent foundation to get