Node.js Telnet Client
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
-
Error: connect ETIMEDOUT
cause The client failed to establish a TCP connection to the specified host and port. This often indicates the Telnet server is not running, is on a different IP/port, a firewall is blocking the connection, or there's a network issue.fixVerify the `host` and `port` parameters are correct. Ensure the Telnet server is running and accessible from the client's network location. Check firewall rules on both client and server. -
UnhandledPromiseRejectionWarning: Telnet connection or command execution error: Timeout
cause The `timeout` duration specified in connection parameters was exceeded before the expected prompt was received or a connection was established, and the resulting promise rejection was not handled.fixImplement proper error handling using `try...catch` around `await connection.connect()` and `await connection.exec()`, or add `.catch()` to your promise chains. Consider increasing the `timeout` value if the server is known to be slow. -
Commands don't execute or hang indefinitely after connecting.
cause The `shellPrompt` parameter is incorrectly configured, leading the client to wait for a prompt that never arrives, or the server's negotiation process is not handled correctly.fixEnsure the `shellPrompt` parameter exactly matches the prompt string displayed by your Telnet server. Alternatively, set `negotiationMandatory: false` in the connection parameters if you want to bypass prompt detection and send commands immediately.
Warnings
- breaking Since version 2.0.0, the `telnet-client` library transitioned from using Bluebird promises to native ES6 Promises. Code relying on Bluebird-specific utilities (e.g., `.tap()`, `.props()`) will break and needs to be updated to use standard Promise methods or async/await.
- gotcha Successful command execution relies heavily on correctly configuring `shellPrompt` or setting `negotiationMandatory: false`. If `shellPrompt` is incorrect, the library may not correctly identify when the server is ready for the next command, leading to hung operations or incorrect command responses.
- gotcha Connections can unexpectedly time out or fail. It's crucial to implement robust error handling for the `connection.connect()` and `connection.exec()` calls, typically with `try...catch` for async/await or `.catch()` for promises, to prevent unhandled promise rejections.
Install
-
npm install telnet-client -
yarn add telnet-client -
pnpm add telnet-client
Imports
- Telnet
const Telnet = require('telnet-client');import { Telnet } from 'telnet-client'; - Telnet client connection
const connection = Telnet();
const connection = new Telnet();
- Type import for parameters
import type { TelnetParams } from 'telnet-client';
Quickstart
'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();