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

Telnet Laravel Package

bestnetwork/telnet

bestnetwork/telnet is a lightweight Telnet client library for PHP, providing basic tools to connect to Telnet servers and send/receive commands over a Telnet session. Suitable for simple automation, diagnostics, and interacting with legacy network services.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package:

    composer require bestnetwork/telnet
    
  2. Basic Connection:

    use BestNetwork\Telnet\Telnet;
    
    $telnet = new Telnet('192.168.1.1', 23); // Host and port
    $telnet->connect();
    
    $telnet->write('login');
    $response = $telnet->read();
    
    $telnet->disconnect();
    
  3. First Use Case: Automate a login sequence for a legacy device:

    $telnet = new Telnet('legacy-device.local', 23);
    $telnet->connect();
    
    $telnet->write('username');
    $telnet->write('password');
    
    $output = $telnet->readUntil('>'); // Read until prompt
    logger()->info('Login output:', ['output' => $output]);
    
    $telnet->disconnect();
    

Where to Look First

  • Core Class: src/Telnet.php – Contains connect(), write(), read(), and disconnect() methods.
  • Tests: tests/ – Example usage and edge cases (e.g., timeouts, malformed responses).
  • README: Basic setup and API reference.

Implementation Patterns

Laravel Integration

  1. Service Container Binding:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->bind(Telnet::class, function () {
            return new Telnet(config('telnet.host'), config('telnet.port'));
        });
    }
    
  2. Artisan Command:

    // app/Console/Commands/CheckDevice.php
    use BestNetwork\Telnet\Telnet;
    
    protected $telnet;
    
    public function __construct(Telnet $telnet)
    {
        $this->telnet = $telnet;
    }
    
    public function handle()
    {
        $this->telnet->connect();
        $this->telnet->write('status');
        $response = $this->telnet->readUntil('OK');
        $this->info($response);
        $this->telnet->disconnect();
    }
    
  3. Queueable Job:

    // app/Jobs/SendTelnetCommand.php
    use BestNetwork\Telnet\Telnet;
    use Illuminate\Bus\Queueable;
    
    public function handle(Telnet $telnet, string $command)
    {
        $telnet->connect();
        $telnet->write($command);
        $response = $telnet->readUntil('>');
    
        // Store or process response
        $this->storeResponse($response);
    }
    

Workflows

  1. Login and Command Execution:

    $telnet = new Telnet('device.ip', 23);
    $telnet->connect();
    
    $telnet->write('login');
    $telnet->write('admin');
    $telnet->write('secret');
    
    $telnet->write('show config');
    $config = $telnet->readUntil('prompt>');
    
    $telnet->disconnect();
    
  2. Timeout Handling:

    $telnet->setTimeout(10); // 10-second timeout
    try {
        $telnet->write('slow-command');
        $response = $telnet->readUntil('OK', 15); // 15-second read timeout
    } catch (\Exception $e) {
        logger()->error('Telnet timeout:', ['error' => $e->getMessage()]);
    }
    
  3. Response Parsing:

    $output = $telnet->read();
    preg_match('/Version: (\d+\.\d+)/', $output, $matches);
    $version = $matches[1] ?? 'unknown';
    

Integration Tips

  • Use Laravel Facades:
    $telnet = resolve(Telnet::class);
    $telnet->connect();
    
  • Configurable Hosts:
    // config/telnet.php
    return [
        'devices' => [
            'router' => ['host' => '192.168.1.1', 'port' => 23],
            'switch' => ['host' => '192.168.1.2', 'port'  => 23],
        ],
    ];
    
  • Async with ReactPHP:
    use React\EventLoop\Factory;
    use BestNetwork\Telnet\Telnet;
    
    $loop = Factory::create();
    $telnet = new Telnet('device.ip', 23);
    
    $loop->futureTick(function () use ($telnet) {
        $telnet->connect();
        $telnet->write('status');
        $response = $telnet->readUntil('>');
        echo $response;
        $telnet->disconnect();
    });
    
    $loop->run();
    

Gotchas and Tips

Pitfalls

  1. Blocking I/O:

    • The package uses synchronous calls by default. For high-concurrency scenarios, wrap calls in Laravel queues or use ReactPHP.
    • Fix: Use spatie/async-command or react/async for async operations.
  2. No Native Error Handling:

    • The package throws generic exceptions. Extend it to use Laravel’s Illuminate\Support\Facades\Log or custom exceptions.
    • Example:
      try {
          $telnet->write('invalid-command');
      } catch (\Exception $e) {
          throw new \RuntimeException("Telnet error: {$e->getMessage()}");
      }
      
  3. Telnet Protocol Limitations:

    • Telnet is unencrypted and deprecated. Avoid using it for sensitive data.
    • Workaround: Use SSH (phpseclib/phpseclib) or VPNs for secure communication.
  4. Connection Leaks:

    • Forgetting to call disconnect() can exhaust system resources.
    • Fix: Use a finally block or Laravel’s ensureClosure:
      $telnet->connect();
      try {
          $telnet->write('command');
      } finally {
          $telnet->disconnect();
      }
      
  5. Timeout Quirks:

    • The default timeout may be too short for slow devices. Adjust with setTimeout().
    • Example:
      $telnet->setTimeout(30); // 30-second timeout
      

Debugging Tips

  1. Enable Verbose Logging:

    $telnet->setDebug(true); // If supported (check package docs)
    logger()->debug('Telnet output:', ['raw' => $telnet->read()]);
    
  2. Mock Telnet for Testing:

    // Use a test double or socat for local testing
    $telnet = Mockery::mock(Telnet::class);
    $telnet->shouldReceive('read')->andReturn('mocked response');
    
  3. Check for EOF:

    • Always verify $telnet->eof() before reading to avoid hanging.
    • Example:
      while (!$telnet->eof()) {
          $data = $telnet->read(1024);
          if (empty($data)) break;
      }
      

Extension Points

  1. Custom Response Parsers:

    class EnhancedTelnet extends Telnet {
        public function parseVersion($output) {
            preg_match('/Version: (\d+\.\d+)/', $output, $matches);
            return $matches[1] ?? null;
        }
    }
    
  2. Retry Middleware:

    use Illuminate\Support\Facades\Retry;
    
    Retry::retry(3, function () use ($telnet) {
        $telnet->connect();
        $telnet->write('command');
        $response = $telnet->readUntil('OK');
        return $response;
    }, 1000); // 1-second delay between retries
    
  3. Laravel Service Provider:

    // Register a custom Telnet instance
    $this->app->singleton('custom.telnet', function () {
        $telnet = new Telnet(config('telnet.host'));
        $telnet->setTimeout(15);
        return $telnet;
    });
    

Config Quirks

  • Port Defaults: The package may default to port 23. Override explicitly:
    $telnet = new Telnet('host', 2323); // Custom port
    
  • Connection Pooling: The package doesn’t support pooling. Implement manually:
    class TelnetPool {
        private $connections = [];
    
        public function get($host) {
            if (!isset($this->connections[$host])) {
                $this->connections[$host] = new Telnet($host);
            }
            return $this->connections[$host];
        }
    }
    

Security Considerations

  • Avoid Hardcoding Credentials: Use Laravel’s config/credentials.php
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony