telnetsession

package module
v0.0.0-...-4a44f3a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 21, 2025 License: MIT Imports: 7 Imported by: 0

README

telnetsession

Go Version Version

Spanish version: README.es.md


The telnetsession package provides an interface for creating and executing telnet sessions on remote devices.

What is a session?

Unlike other telnet packages, with telnetsession you must define a session using telnetsession.NewBuilder(). In this configuration you can specify parameters such as timeout, Enter character, prompt, among others. Additionally, you must declare the actions to execute using Send(), Expect() and their variants.

Once you have declared all the actions in a session, you can execute it. This approach provides you with more precise control when sending commands and handling responses, plus it offers better error handling.

A standout feature is the ability to send templates (https://pkg.go.dev/text/template) and use dynamic data to generate commands programmatically.

Features

  • Fluid action system for sending commands and waiting for responses
  • Template support that allows generating commands dynamically
  • Success callbacks for automatically processing responses
  • Integrated login handling with username and password
  • Configurable timeouts for connection, reading and writing
  • Builder interface for fluid and readable configuration

Installation

go get github.com/WinAndronuX/telnetsession

Basic Usage

Simple Example
package main

import (
    "fmt"
    "log"
    "time"
    
    "github.com/WinAndronuX/telnetsession"
)

func main() {
    // Configure the session
    session, err := telnetsession.NewBuilder().
        WithTimeout(5 * time.Second).
        SetEnter("\n").
        SetLoginExpr("Login:", "Password:").
        SetPrompt(">").
        Send("show version").
        Build()
    
    if err != nil {
        log.Fatal(err)
    }
    
    // Create and execute the session
    device := telnetsession.New(session)
    
    if err := device.Run("192.168.1.1", 23, "admin", "password"); err != nil {
        log.Fatal(err)
    }
    
    // Get the output
    fmt.Println(device.GetOutput())
}
Example with Callbacks
session, err := telnetsession.NewBuilder().
    WithTimeout(5 * time.Second).
    SetEnter("\n").
    SetLoginExpr("Login:", "Password:").
    SetPrompt(">").
    Send("enable").
    SetPrompt("#").
    Expect("Password:").
    Send("enable_password").
    SendAndDo("show version", func(output string) error {
        fmt.Println("Device version:", output)
        return nil
    }).
    Build()
Example with Templates
data := map[string]any{
    "interfaces": []string{"eth0", "eth1", "eth2"},
}

session, err := telnetsession.NewBuilder().
    WithTimeout(5 * time.Second).
    SetEnter("\n").
    SetLoginExpr("Login:", "Password:").
    SetPrompt(">").
    SendTempl(`
{{ range .interfaces }}
interface {{ . }}
show interface
exit
{{ end }}`, data).
    Build()

API Reference

SessionBuilder

The SessionBuilder provides a fluid interface for configuring telnet sessions.

Configuration Methods
  • WithTimeout(duration) - Sets the connection timeout
  • WithReadTimeout(duration) - Sets the read timeout
  • WithWriteTimeout(duration) - Sets the write timeout
  • SetEnter(string) - Sets the end-of-line character
  • SetPrompt(string) - Sets the prompt character
  • SetLoginExpr(username, password) - Sets the login expressions
Action Methods
  • Send(text) - Sends text to the device
  • SendAndDo(text, callback) - Sends text and executes a callback to process the response
  • SendTempl(template, data) - Sends a template
  • SendTemplAndDo(template, data, callback) - Sends a template and executes a callback to process the response
  • Expect(text) - Waits for a specific text to appear
  • ExpectAndDo(text, callback) - Waits for specific text and executes a callback to process the response
TelnetSession

The main telnet session that handles the connection and executes the actions.

Main Methods
  • Run(host, port, user, pass) - Executes the complete session
  • GetOutput() - Gets the accumulated output from the session

Best Practices

  • Automatic prompt management: It's not necessary to manually wait for the prompt (#, >, $) using Expect("#"), as the library handles this automatically. Ignoring this recommendation can cause unexpected errors.

  • SetEnter configuration: The SetEnter method should be configured only once and always before declaring any actions. If not specified, the default character is \n.

Timeout Configuration

session, err := telnetsession.NewBuilder().
    WithTimeout(10 * time.Second).        // Connection timeout
    WithReadTimeout(5 * time.Second).     // Read timeout
    WithWriteTimeout(3 * time.Second).    // Write timeout
    // ... rest of configuration
    Build()

Prompt Handling

Prompts are used to wait for device responses after sending commands:

session, err := telnetsession.NewBuilder().
    SetPrompt(">").           // Normal prompt
    Send("enable").
    SetPrompt("#").           // Privileged prompt
    Send("configure terminal").
    SetPrompt("(config)#").   // Configuration prompt
    Build()

Success Callbacks

Callbacks allow automatically processing responses:

session, err := telnetsession.NewBuilder().
    SendAndDo("show interfaces", func(output string) error {
        // Process command output
        if strings.Contains(output, "up") {
            fmt.Println("Active interface found")
        }
        return nil
    }).
    Build()

Templates

Templates allow generating commands dynamically using Go template syntax:

data := map[string]any{
    "vlans": []int{10, 20, 30},
    "name": "VLAN_",
}

session, err := telnetsession.NewBuilder().
    SendTempl(`
{{ range .vlans }}
vlan {{ . }}
name {{ $.name }}{{ . }}
exit
{{ end }}`, data).
    Build()

Examples

Click here

Error Handling

The library provides descriptive errors to facilitate debugging:

if err := device.Run(host, port, user, pass); err != nil {
    log.Printf("Session error: %v", err)
    return
}

Requirements

  • Go 1.23 or higher

License

This project is under the MIT license.

Contributions

Contributions are welcome. Please open an issue or pull request for suggestions or improvements.

Documentation

Overview

Package telnetsession provides a fluent interface for creating and executing telnet sessions with remote devices.

The library is designed to simplify telnet automation by providing a builder pattern for defining session actions and a clean API for executing them.

Basic Usage

Create a session using the builder pattern:

session, err := telnetsession.NewBuilder().
	WithTimeout(5 * time.Second).
	SetEnter("\n").
	SetLoginExpr("Login:", "Password:").
	SetPrompt(">").
	Send("show version").
	Build()

if err != nil {
	log.Fatal(err)
}

device := telnetsession.New(session)
err = device.Run("192.168.1.1", 23, "admin", "password")

Session Configuration

The SessionBuilder provides several methods for configuring the session:

- WithTimeout(duration): Sets connection timeout - WithReadTimeout(duration): Sets the read timeout for individual read operations - WithWriteTimeout(duration): Sets the write timeout for individual write operations - SetEnter(string): Sets line ending character(s) - SetPrompt(string): Sets prompt character to wait for after commands - SetLoginExpr(username, password): Sets text patterns for login prompts

Actions

The library supports two types of actions:

## Expect Actions Wait for specific text to appear in the session:

builder.Expect("Welcome")
builder.ExpectAndDo("Error", func(output string) error {
	// Handle error condition
	return nil
})

## Send Actions Send commands to the remote device:

builder.Send("configure terminal")
builder.SendAndDo("show version", func(output string) error {
	// Process output
	return nil
})

## Template Actions Send templated commands with dynamic data:

data := map[string]any{
	"interfaces": []string{"eth0", "eth1", "eth2"},
}

builder.SendTempl(`

{{ range .interfaces }} interface {{ . }} show interface {{ end }}`, data)

Error Handling

The library provides comprehensive error handling:

- Connection errors are wrapped with context - Template parsing errors are collected during building - Action execution errors include action index and context - Validation errors for invalid parameters

Output Processing

The TelnetSession accumulates all output and provides a GetOutput() method that:

- Removes duplicate empty lines - Preserves command output structure - Returns clean, formatted output

Examples

See the examples/ directory for complete working examples:

- examples/vsol/: Basic session with VSOL device - examples/vsoltempl/: Session using templates for dynamic commands

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Action

type Action interface {
	// GetType returns the type of this action
	GetType() ActionType
	// GetText returns the text associated with this action
	GetText() (string, error)
	// GetPrompt returns the prompt character to wait for after sending text
	GetPrompt() string
	// SetPrompr
	SetPrompt(prompt string)
	// GetOnSuccessFunc returns the callback function to execute on success
	GetOnSuccessFunc() OnSuccessFunc
}

Action defines the interface that all session actions must implement

type ActionType

type ActionType int

ActionType represents the type of action that can be performed in a telnet session

const (
	// ActionExpect represents an action that waits for specific text to appear
	ActionExpect ActionType = iota
	// ActionSend represents an action that sends text to the remote device
	ActionSend
)

type ExpectAction

type ExpectAction struct {
	OnSuccessFunc OnSuccessFunc
	// contains filtered or unexported fields
}

ExpectAction represents an action that waits for specific text to appear in the session

func (*ExpectAction) GetOnSuccessFunc

func (e *ExpectAction) GetOnSuccessFunc() OnSuccessFunc

GetOnSuccessFunc returns the success callback function

func (*ExpectAction) GetPrompt

func (e *ExpectAction) GetPrompt() string

GetPrompt returns an empty string as ExpectAction doesn't use prompts

func (*ExpectAction) GetText

func (e *ExpectAction) GetText() (string, error)

GetText returns the text to expect, always returns the text without error

func (*ExpectAction) GetType

func (e *ExpectAction) GetType() ActionType

GetType returns ActionExpect for ExpectAction

func (*ExpectAction) SetPrompt

func (e *ExpectAction) SetPrompt(_ string)

type OnSuccessFunc

type OnSuccessFunc func(value string) error

OnSuccessFunc is a callback function that gets executed when an action completes successfully The function receives the output value as a string and can return an error

type SendAction

type SendAction struct {
	// contains filtered or unexported fields
}

SendAction represents an action that sends templated text to the remote device

func (*SendAction) GetOnSuccessFunc

func (s *SendAction) GetOnSuccessFunc() OnSuccessFunc

GetOnSuccessFunc returns the success callback function

func (*SendAction) GetPrompt

func (s *SendAction) GetPrompt() string

GetPrompt returns the prompt character to wait for after sending text

func (*SendAction) GetText

func (s *SendAction) GetText() (string, error)

GetText executes the template with the provided data and returns the resulting text

func (*SendAction) GetType

func (s *SendAction) GetType() ActionType

GetType returns ActionSend for SendAction

func (*SendAction) SetPrompt

func (s *SendAction) SetPrompt(prompt string)

type Session

type Session struct {
	// Actions is the sequence of actions to execute during the session
	Actions []Action
	// Enter is the line ending character(s) to use when sending commands
	Enter string
	// Prompt is the character to wait for after sending commands (e.g., ">", "#", "$")
	Prompt string
	// ExprUser is the text pattern to expect when prompting for username
	ExprUser string
	// ExprPass is the text pattern to expect when prompting for password
	ExprPass string
	// Timeout is the connection timeout duration. Use 0 for no timeout
	Timeout time.Duration
	// ReadTimeout is the timeout for read operations. Use 0 for no timeout
	ReadTimeout time.Duration
	// WriteTimeout is the timeout for write operations. Use 0 for no timeout
	WriteTimeout time.Duration
}

Session represents a telnet session configuration with a sequence of actions to perform

type SessionBuilder

type SessionBuilder struct {
	// contains filtered or unexported fields
}

SessionBuilder provides a fluent interface for building Session configurations

func NewBuilder

func NewBuilder() *SessionBuilder

NewBuilder creates a new SessionBuilder instance with default settings

func (*SessionBuilder) Build

func (s *SessionBuilder) Build() (*Session, error)

Build creates a Session instance from the builder configuration Returns an error if any template parsing errors occurred during building

func (*SessionBuilder) Confirm

func (s *SessionBuilder) Confirm(prompt, message string) *SessionBuilder

func (*SessionBuilder) Expect

func (s *SessionBuilder) Expect(text string) *SessionBuilder

Expect adds an action that waits for the specified text to appear

func (*SessionBuilder) ExpectAndDo

func (s *SessionBuilder) ExpectAndDo(text string, onSuccess OnSuccessFunc) *SessionBuilder

ExpectAndDo adds an action that waits for the specified text and executes a callback on success

func (*SessionBuilder) Send

func (s *SessionBuilder) Send(text string) *SessionBuilder

Send adds an action that sends the specified text to the remote device

func (*SessionBuilder) SendAndDo

func (s *SessionBuilder) SendAndDo(text string, onSuccess OnSuccessFunc) *SessionBuilder

SendAndDo adds an action that sends text and executes a callback on success

func (*SessionBuilder) SendTempl

func (s *SessionBuilder) SendTempl(text string, data map[string]any) *SessionBuilder

SendTempl adds an action that sends templated text with the provided data

func (*SessionBuilder) SendTemplAndDo

func (s *SessionBuilder) SendTemplAndDo(text string, data map[string]any, onSuccess OnSuccessFunc) *SessionBuilder

SendTemplAndDo adds an action that sends templated text and executes a callback on success

func (*SessionBuilder) SetEnter

func (s *SessionBuilder) SetEnter(enter string) *SessionBuilder

SetEnter sets the line ending character(s) to use when sending commands

func (*SessionBuilder) SetLoginExpr

func (s *SessionBuilder) SetLoginExpr(username, password string) *SessionBuilder

SetLoginExpr sets the text patterns to expect for username and password prompts

func (*SessionBuilder) SetPrompt

func (s *SessionBuilder) SetPrompt(value string) *SessionBuilder

SetPrompt sets the prompt character to wait for after sending commands

func (*SessionBuilder) WithReadTimeout

func (s *SessionBuilder) WithReadTimeout(timeout time.Duration) *SessionBuilder

WithReadTimeout sets the read timeout for individual read operations

func (*SessionBuilder) WithTimeout

func (s *SessionBuilder) WithTimeout(timeout time.Duration) *SessionBuilder

WithTimeout sets the connection timeout for the session

func (*SessionBuilder) WithWriteTimeout

func (s *SessionBuilder) WithWriteTimeout(timeout time.Duration) *SessionBuilder

WithWriteTimeout sets the write timeout for individual write operations

type TelnetSession

type TelnetSession struct {
	// contains filtered or unexported fields
}

TelnetSession manages a telnet connection and executes session actions

func New

func New(session *Session) *TelnetSession

New creates a new TelnetSession with the provided session configuration

func (*TelnetSession) GetOutput

func (t *TelnetSession) GetOutput() string

GetOutput returns the accumulated output from the session, with duplicate empty lines removed

func (*TelnetSession) Run

func (t *TelnetSession) Run(host string, port int, user, pass string) error

Run establishes a telnet connection and executes the configured session actions

Directories

Path Synopsis
examples
vsol command
vsoltempl command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL