Node.js Telnet Client

2.2.13 · active · verified Tue Apr 21

telnet-client is a straightforward Node.js library for establishing and interacting with Telnet servers. As of its current stable version, 2.2.13, it offers modern asynchronous interfaces using native ES6 Promises and async/await syntax, a significant update from version 2.0.0 which transitioned away from Bluebird promises. It also retains support for callback-style interactions. The library focuses on providing core Telnet client functionality, including connection management, command execution, and event handling for 'ready', 'timeout', and 'close' states. Its release cadence appears to be moderate, with updates addressing compatibility and feature improvements. A key differentiator is its simplicity and explicit handling of shell prompts or the option to bypass negotiation, which is crucial for interacting with diverse Telnet server implementations.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates connecting to a Telnet server, executing a command, and handling potential errors using async/await.

'use strict';
import { Telnet } from 'telnet-client';

async function runTelnetClient() {
  const connection = new Telnet();

  // These parameters are just examples. Adjust them for your specific Telnet server.
  const params = {
    host: '127.0.0.1', // Replace with your Telnet server's host
    port: 23,          // Replace with your Telnet server's port (default Telnet is 23)
    shellPrompt: '/ # ', // Important: Set this to your server's prompt, or negotiationMandatory: false
    timeout: 3000,       // Connection timeout in milliseconds
    negotiationMandatory: true, // Set to false if you don't need prompt detection and want to send commands directly
    // You might also need to configure 'irs' (input response string) and 'ors' (output response string)
    // depending on how your Telnet server responds and expects input.
  };

  try {
    console.log(`Attempting to connect to ${params.host}:${params.port}...`);
    await connection.connect(params);
    console.log('Connected to Telnet server.');

    // Example: Execute a command like 'uptime'
    const command = 'uptime';
    console.log(`Executing command: "${command}"`);
    const response = await connection.exec(command);
    console.log(`Command response: ${response.trim()}`);

    // Example: Send multiple commands
    // await connection.exec('ls -l');
    // console.log('Executed ls -l');

    connection.end();
    console.log('Connection closed.');
  } catch (error: any) {
    console.error('Telnet connection or command execution error:', error.message);
    // Ensure the connection is closed even on error
    if (connection.socket && !connection.socket.destroyed) {
        connection.end();
    }
  }
}

runTelnetClient();

view raw JSON →