vezssh

package module
v0.0.0-...-7b3bb31 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2026 License: MIT Imports: 25 Imported by: 0

README

VezSSH - Enhanced SSH Library for Go

🌟 Advanced SSH library with multi-jump host support and comprehensive tunneling capabilities

Go Version


🚀 Overview | ภาพรวมโครงการ

VezSSH is a powerful Go SSH library that extends the capabilities of easyssh-proxy with advanced features for modern SSH operations. It provides a high-level, easy-to-use API for SSH connections, command execution, file transfers, and sophisticated proxy tunneling.

VezSSH เป็นไลบรารี SSH สำหรับ Go ที่ขยายความสามารถจาก easyssh-proxy ด้วยฟีเจอร์ขั้นสูงสำหรับการใช้งาน SSH สมัยใหม่ โดยมี API ระดับสูงที่ใช้งานง่าย สำหรับการเชื่อมต่อ SSH, การรันคำสั่ง, การถ่ายโอนไฟล์, และการทำ proxy tunneling ที่ซับซ้อน

✨ Key Features | ฟีเจอร์หลัก
  • 🔗 Multi-Jump Host Support - Chain multiple SSH jump hosts
  • 🔄 Forward/Reverse Tunneling - Create secure tunnels between hosts
  • 🧦 SOCKS5 Proxy - Dynamic port forwarding with SOCKS5
  • 📁 File Transfer - Both SCP and SFTP support
  • Streaming Execution - Real-time command output streaming
  • 🔐 Flexible Authentication - Private key, password, and key file support
  • 🧪 Comprehensive Testing - 112+ unit tests with mock SSH server

📁 Project Structure | โครงสร้างโครงการ

vezssh/
├── vezssh.go          # Core types and configuration
├── connect.go         # SSH connection management
├── internal.go        # Authentication and helper functions
├── stream.go          # Command execution (streaming & blocking)
├── scp.go            # SCP file transfer implementation
├── sftp.go           # SFTP file transfer implementation
├── tunnel.go         # Port forwarding and tunneling
├── socks5.go         # SOCKS5 proxy implementation
├── log.go            # Logging utilities
├── *_test.go         # Comprehensive test suite
└── TEST_*.md         # Detailed test documentation
🏗️ Architecture | สถาปัตยกรรม
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Jump Host 1   │───▶│   Jump Host 2   │───▶│  Target Server  │
│  proxy.com:22   │    │  gateway.com:22 │    │  server.com:22  │
└─────────────────┘    └─────────────────┘    └─────────────────┘
                                               ▲
                                               │
                                          ┌────────┐
                                          │ Client │
                                          └────────┘

🛠️ Installation | การติดตั้ง

go get beargit.com/vezssh/vezssh
Prerequisites | ข้อกำหนดเบื้องต้น
  • Go 1.18+ (locked for gccgo 12.1 compatibility)
  • SSH access to target servers
  • Private key files or password authentication

📖 Usage Examples | ตัวอย่างการใช้งาน

Basic SSH Connection | การเชื่อมต่อ SSH พื้นฐาน
package main

import (
    "fmt"
    "log"
    "beargit.com/vezssh/vezssh"
)

func main() {
    // Create SSH configuration
    config := &vezssh.Config{
        User:     "ubuntu",
        Server:   "example.com", 
        Port:     "22",
        KeyPath:  "/home/user/.ssh/id_rsa",
        Timeout:  30 * time.Second,
    }

    // Execute command
    stdout, stderr, done, err := config.Run("ls -la")
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Println("Output:", stdout)
    fmt.Println("Error:", stderr) 
    fmt.Println("Exit Code:", done)
}
Multi-Jump Host Setup | การตั้งค่า Jump Host หลายขั้น
config := &vezssh.Config{
    User:   "user",
    Server: "target-server.com",
    Port:   "22", 
    KeyPath: "/path/to/private/key",
    JumpHosts: []vezssh.DefaultConfig{
        {
            User:   "proxy1",
            Server: "jump1.example.com",
            Port:   "22",
            KeyPath: "/path/to/jump1/key",
        },
        {
            User:   "proxy2", 
            Server: "jump2.example.com",
            Port:   "2222",
            KeyPath: "/path/to/jump2/key",
        },
    },
}

// Execute command through jump hosts
stdout, _, _, err := config.Run("hostname")
File Transfer | การถ่ายโอนไฟล์
// SCP Upload
err := config.Scp("/local/file.txt", "/remote/path/file.txt")

// SCP Download  
err := config.ScpDownload("/remote/file.txt", "/local/file.txt")

// SFTP Operations
sftpClient, err := config.NewSftp()
if err != nil {
    log.Fatal(err)
}
defer sftpClient.Close()

err = sftpClient.Upload("/local/file.txt", "/remote/file.txt")
Port Forwarding | การทำ Port Forwarding
// Forward tunnel (Local -> Remote)
tunnel := vezssh.Tunnel{
    Mode:      vezssh.TunModeFwd,
    BindAddr:  "localhost:8080", 
    RemoteAddr: "internal-server:80",
}

err := config.BindTunnel(tunnel)

// Reverse tunnel (Remote -> Local)
reverseTunnel := vezssh.Tunnel{
    Mode:      vezssh.TunModeRev,
    BindAddr:  "0.0.0.0:9090",
    RemoteAddr: "localhost:3000", 
}

err := config.BindTunnel(reverseTunnel)

// SOCKS5 Dynamic Proxy
socksTunnel := vezssh.Tunnel{
    Mode:     vezssh.TunModeDyn,
    BindAddr: "localhost:1080",
}

err := config.BindTunnel(socksTunnel)
Streaming Command Execution | การรันคำสั่งแบบ Stream
// Stream real-time output
output, session, err := config.Stream("tail -f /var/log/syslog")
if err != nil {
    log.Fatal(err)
}
defer session.Close()

// Read streaming output
for line := range output {
    fmt.Println("Log:", line)
}

🧪 Testing | การทดสอบ

The project includes comprehensive testing with a sophisticated mock SSH server:

โครงการมีการทดสอบอย่างครอบคลุมด้วย mock SSH server ที่ซับซ้อน:

# Run all tests
go test -v

# Run quick tests only (skip integration tests)
go test -v -short

# Run specific test component
go test -v -run "TestConfig_Connect"

# Run with timeout to prevent hangs
timeout 60 go test -v
Test Coverage | ความครอบคลุมการทดสอบ
  • ✅ 112+ unit tests
  • ✅ Mock SSH server for realistic testing
  • ✅ Authentication method testing
  • ✅ Jump host chain validation
  • ✅ Error handling scenarios
  • ✅ Connection lifecycle management

🤝 Contributing | การร่วมพัฒนา

We welcome contributions from developers who are interested in:

เรายินดีต้อนรับการมีส่วนร่วมจากนักพัฒนาที่สนใจใน:

🎯 Areas of Interest | ด้านที่น่าสนใจ
  • SSH Protocol Experts - Enhance SSH feature support
  • Security Specialists - Improve authentication mechanisms
  • Network Engineers - Optimize tunneling performance
  • Go Developers - Code quality and performance improvements
  • Documentation Writers - Improve docs and examples
  • Testing Enthusiasts - Expand test coverage
🔧 Development Areas | ด้านการพัฒนา
  • Connection Pooling - Implement reusable connection pools
  • IPv6 Support - Add full IPv6 compatibility
  • Certificate Authentication - Support SSH certificates
  • Agent Forwarding - SSH agent forwarding support
  • Async Operations - Non-blocking async API
  • Performance Optimization - Memory and CPU improvements
📝 How to Contribute | วิธีการมีส่วนร่วม
  1. Fork the repository | Fork repository
  2. Create feature branch | สร้าง feature branch
    git checkout -b feature/awesome-feature
    
  3. Make changes | ทำการเปลี่ยนแปลง
  4. Add tests | เพิ่มการทดสอบ
    go test -v
    
  5. Submit pull request | ส่ง pull request
🎨 Code Style Guidelines | แนวทางการเขียนโค้ด
  • Follow standard Go conventions
  • Add comprehensive tests for new features
  • Update documentation for API changes
  • Use meaningful commit messages
  • Ensure backwards compatibility

📚 Documentation | เอกสารประกอบ


🐛 Issues & Support | ปัญหาและการสนับสนุน

  • Bug Reports | รายงานข้อผิดพลาด: Create GitHub issues with detailed reproduction steps
  • Feature Requests | ขอฟีเจอร์ใหม่: Describe use cases and expected behavior
  • Questions | คำถาม: Use GitHub Discussions for general questions

📄 License | ใบอนุญาต

This project is licensed under the MIT License - see the LICENSE file for details.

โครงการนี้อยู่ภายใต้ MIT License - ดูรายละเอียดในไฟล์ LICENSE


🙏 Acknowledgments | คำขอบคุณ



Happy Coding! 🚀 | เขียนโค้ดให้สนุก! 🚀

Documentation

Overview

SSH Agent Forwarding implementation for VezSSH v2.0 Provides SSH agent forwarding support for seamless key management

Async Operations implementation for VezSSH v2.0 Provides non-blocking asynchronous operations for improved performance

SSH Certificate Authentication implementation for VezSSH v2.0 Provides support for SSH certificates as an alternative to traditional public key authentication

IPv6 Support implementation for VezSSH v2.0 Provides comprehensive IPv6 connectivity and dual-stack support

Connection Pool implementation for VezSSH v2.0 Provides reusable SSH connection management with automatic cleanup

Connection Retry and Reconnection Logic for VezSSH v2.0 Provides automatic reconnection with exponential backoff

Resumable File Transfer Implementation for VezSSH v2.0 Provides SFTP transfers with automatic resume and reconnection within a single session

SFTP-backed fs.FS implementation for VezSSH. Provides Go's io/fs interfaces using an SFTP connection as the backend.

INSPIRE FROM https://gist.github.com/afdalwahyu/4c70868c84e68676c86e1a54b410655d

MOST OF THIS FILE CONTENT CAME FROM https://gist.github.com/0187773933/0f1061d6ada5333dbe462ae2bacd7bbd WITH SOME MODIFICATION

Package easyssh provides a simple implementation of some SSH protocol features in Go. You can simply run a command on a remote server or get a file even simpler than native console SSH client. You don't need to think about Dials, sessions, defers, or public keys... Let easyssh think about it!

Index

Constants

This section is empty.

Variables

View Source
var ErrTransferCancelled = errors.New("transfer cancelled by user")

ErrTransferCancelled is returned when the user cancels a transfer via the progress callback.

Functions

func BindTunnels

func BindTunnels(tunnels []Tunnel)

Types

type AgentConfig

type AgentConfig struct {
	*Config
	EnableAgentForwarding bool          // Enable SSH agent forwarding
	AgentSocketPath       string        // Path to SSH agent socket
	AgentTimeout          time.Duration // Timeout for agent operations
	ForwardToRemote       bool          // Forward agent to remote server
	LocalAgent            agent.Agent   // Local SSH agent
}

AgentConfig extends Config with SSH agent support

func NewAgentConfig

func NewAgentConfig(config *Config) *AgentConfig

NewAgentConfig creates a new agent-enabled config

func (*AgentConfig) ConnectToAgent

func (c *AgentConfig) ConnectToAgent() (agent.Agent, error)

ConnectToAgent connects to SSH agent

func (*AgentConfig) ConnectWithAgent

func (c *AgentConfig) ConnectWithAgent() (*ssh.Client, error)

ConnectWithAgent establishes SSH connection using agent authentication

func (*AgentConfig) CreateAgentAuth

func (c *AgentConfig) CreateAgentAuth() (ssh.AuthMethod, error)

CreateAgentAuth creates SSH auth method using agent

func (*AgentConfig) CreateSessionWithAgent

func (c *AgentConfig) CreateSessionWithAgent(client *ssh.Client) (*AgentForwardingSession, error)

CreateSessionWithAgent creates a session with agent forwarding

func (*AgentConfig) ForwardAgent

func (c *AgentConfig) ForwardAgent(session *ssh.Session) error

ForwardAgent sets up agent forwarding for a session

func (*AgentConfig) GetAgentKeys

func (c *AgentConfig) GetAgentKeys() ([]*agent.Key, error)

GetAgentKeys retrieves keys from SSH agent

func (*AgentConfig) ListAgentKeys

func (c *AgentConfig) ListAgentKeys() ([]AgentKeyInfo, error)

ListAgentKeys lists all keys in the SSH agent with details

func (*AgentConfig) RunWithAgent

func (c *AgentConfig) RunWithAgent(command string, timeout ...time.Duration) (string, string, bool, error)

RunWithAgent runs a command with agent forwarding

func (*AgentConfig) TestAgentConnection

func (c *AgentConfig) TestAgentConnection() error

TestAgentConnection tests if agent connection is working

type AgentForwardingConfig

type AgentForwardingConfig struct {
	Enable       bool          // Enable agent forwarding
	LocalSocket  string        // Local agent socket path
	RemoteSocket string        // Remote agent socket path
	Timeout      time.Duration // Operation timeout
	BufferSize   int           // Buffer size for forwarding
	KeepAlive    bool          // Enable keep-alive
	KeepInterval time.Duration // Keep-alive interval
}

AgentForwardingConfig configures agent forwarding behavior

func DefaultAgentForwardingConfig

func DefaultAgentForwardingConfig() AgentForwardingConfig

DefaultAgentForwardingConfig returns default agent forwarding configuration

type AgentForwardingSession

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

AgentForwardingSession manages agent forwarding for a session

func (*AgentForwardingSession) Close

func (afs *AgentForwardingSession) Close() error

Close closes the agent forwarding session

type AgentKeyInfo

type AgentKeyInfo struct {
	Blob        []byte
	Comment     string
	Format      string
	Type        string
	Fingerprint string
}

AgentKeyInfo represents information about a key in the agent

type AgentManager

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

AgentManager manages multiple agent connections

func NewAgentManager

func NewAgentManager() *AgentManager

NewAgentManager creates a new agent manager

func (*AgentManager) AddAgent

func (am *AgentManager) AddAgent(name string, agentConn agent.Agent)

AddAgent adds an agent to the manager

func (*AgentManager) GetAgent

func (am *AgentManager) GetAgent(name string) (agent.Agent, bool)

GetAgent retrieves an agent by name

func (*AgentManager) ListAgents

func (am *AgentManager) ListAgents() []string

ListAgents returns names of all managed agents

func (*AgentManager) RemoveAgent

func (am *AgentManager) RemoveAgent(name string)

RemoveAgent removes an agent from the manager

type AsyncConfig

type AsyncConfig struct {
	*Config
	MaxConcurrentOps int           // Maximum concurrent operations
	OperationTimeout time.Duration // Default timeout for operations
	RetryAttempts    int           // Number of retry attempts
	RetryDelay       time.Duration // Delay between retries
	// contains filtered or unexported fields
}

AsyncConfig extends Config with async operation support

func NewAsyncConfig

func NewAsyncConfig(config *Config) *AsyncConfig

NewAsyncConfig creates a new async-enabled config

func (*AsyncConfig) ConnectAsync

func (c *AsyncConfig) ConnectAsync() (*AsyncOperation, error)

ConnectAsync establishes SSH connection asynchronously

func (*AsyncConfig) GetActiveOperations

func (c *AsyncConfig) GetActiveOperations() []string

GetActiveOperations returns the IDs of currently running async operations.

func (*AsyncConfig) GetResult

func (c *AsyncConfig) GetResult(id string) (*AsyncResult, bool)

GetResult returns the result of a previously submitted async operation.

func (*AsyncConfig) RunAsync

func (c *AsyncConfig) RunAsync(command string, timeout ...time.Duration) (*AsyncOperation, error)

RunAsync executes a command asynchronously

func (*AsyncConfig) ScpAsync

func (c *AsyncConfig) ScpAsync(localFile, remoteFile string) (*AsyncOperation, error)

ScpAsync transfers a file asynchronously using SCP

func (*AsyncConfig) StreamAsync

func (c *AsyncConfig) StreamAsync(command string) (*AsyncOperation, error)

StreamAsync executes a command with streaming output asynchronously

func (*AsyncConfig) WaitForAll

func (c *AsyncConfig) WaitForAll()

WaitForAll blocks until all async operations submitted through this config complete.

type AsyncManager

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

AsyncManager manages asynchronous operations

func NewAsyncManager

func NewAsyncManager(maxConcurrent int) *AsyncManager

NewAsyncManager creates a new async operation manager

func (*AsyncManager) CancelOperation

func (am *AsyncManager) CancelOperation(id string) bool

CancelOperation cancels an operation

func (*AsyncManager) GetActiveOperations

func (am *AsyncManager) GetActiveOperations() []string

GetActiveOperations returns list of active operation IDs

func (*AsyncManager) GetResult

func (am *AsyncManager) GetResult(id string) (*AsyncResult, bool)

GetResult gets the result of an operation

func (*AsyncManager) GetStats

func (am *AsyncManager) GetStats() AsyncStats

GetStats returns async operation statistics

func (*AsyncManager) SubmitBatch

func (am *AsyncManager) SubmitBatch(batchID string, operations []func(context.Context) (any, error)) *BatchOperation

SubmitBatch submits a batch of operations

func (*AsyncManager) SubmitOperation

func (am *AsyncManager) SubmitOperation(id, opType string, fn func(context.Context) (any, error)) *AsyncOperation

SubmitOperation submits an async operation

func (*AsyncManager) WaitForAll

func (am *AsyncManager) WaitForAll()

WaitForAll waits for all operations to complete

type AsyncOperation

type AsyncOperation struct {
	ID      string
	Type    string
	Fn      func(context.Context) (any, error)
	Context context.Context
	Cancel  context.CancelFunc
	Result  chan *AsyncResult
	// contains filtered or unexported fields
}

AsyncOperation represents an async operation

type AsyncResult

type AsyncResult struct {
	ID        string    // Operation ID
	Operation string    // Operation type
	Result    any       // Operation result
	Error     error     // Operation error
	StartTime time.Time // Operation start time
	EndTime   time.Time // Operation end time
	Duration  time.Duration
}

AsyncResult represents the result of an async operation

type AsyncStats

type AsyncStats struct {
	TotalOperations      int
	CompletedOperations  int
	FailedOperations     int
	ActiveOperations     int
	AverageExecutionTime time.Duration
	TotalExecutionTime   time.Duration
}

AsyncStats provides statistics about async operations

type BatchOperation

type BatchOperation struct {
	ID         string
	Operations []*AsyncOperation
	Results    []*AsyncResult
	StartTime  time.Time
	EndTime    time.Time
	// contains filtered or unexported fields
}

BatchOperation represents a batch of operations

func (*BatchOperation) GetProgress

func (batch *BatchOperation) GetProgress() float64

GetProgress returns batch completion progress (0.0 to 1.0)

func (*BatchOperation) WaitForCompletion

func (batch *BatchOperation) WaitForCompletion() []*AsyncResult

WaitForCompletion waits for a batch to complete without busy-waiting.

type CertificateAuthMethod

type CertificateAuthMethod struct {
}

CertificateAuthMethod creates SSH authentication method using certificates

type CertificateConfig

type CertificateConfig struct {
	*Config
	CertificateData     []byte        // Certificate data as bytes
	CertificatePath     string        // Path to certificate file
	PrivateKeyData      []byte        // Private key data as bytes
	PrivateKeyPath      string        // Path to private key file
	ValidateCA          bool          // Validate certificate against CA
	CAKeysPath          string        // Path to CA public keys
	AllowedPrincipals   []string      // Allowed certificate principals
	MaxCertLifetime     time.Duration // Maximum certificate lifetime to accept
	RequireSourceAddr   bool          // Require source address extension
	RequireForceCommand bool          // Require force command extension
}

CertificateConfig extends Config with SSH certificate support

func NewCertificateConfig

func NewCertificateConfig(config *Config) *CertificateConfig

NewCertificateConfig creates a new certificate-enabled config

func (*CertificateConfig) ConnectWithCertificate

func (c *CertificateConfig) ConnectWithCertificate() (*ssh.Client, error)

ConnectWithCertificate establishes SSH connection using certificate authentication

func (*CertificateConfig) CreateCertificateAuth

func (c *CertificateConfig) CreateCertificateAuth() (ssh.AuthMethod, error)

CreateCertificateAuth creates SSH auth method for certificate

func (*CertificateConfig) LoadCertificateFromData

func (c *CertificateConfig) LoadCertificateFromData(certData []byte) (*SSHCertificate, error)

LoadCertificateFromData loads SSH certificate from byte data

func (*CertificateConfig) LoadCertificateFromFile

func (c *CertificateConfig) LoadCertificateFromFile() (*SSHCertificate, error)

LoadCertificateFromFile loads SSH certificate from file

func (*CertificateConfig) ValidateCertificate

func (c *CertificateConfig) ValidateCertificate(cert *SSHCertificate) error

ValidateCertificate validates the SSH certificate

type CertificateManager

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

CertificateManager manages multiple certificates

func NewCertificateManager

func NewCertificateManager() *CertificateManager

NewCertificateManager creates a new certificate manager

func (*CertificateManager) AddCertificate

func (cm *CertificateManager) AddCertificate(name string, cert *SSHCertificate)

AddCertificate adds a certificate to the manager

func (*CertificateManager) GetCertificate

func (cm *CertificateManager) GetCertificate(name string) (*SSHCertificate, bool)

GetCertificate retrieves a certificate by name

func (*CertificateManager) GetDefaultCertificate

func (cm *CertificateManager) GetDefaultCertificate() (*SSHCertificate, bool)

GetDefaultCertificate returns the default certificate

func (*CertificateManager) ListCertificates

func (cm *CertificateManager) ListCertificates() []string

ListCertificates returns names of all certificates

func (*CertificateManager) RemoveExpiredCertificates

func (cm *CertificateManager) RemoveExpiredCertificates() int

RemoveExpiredCertificates removes expired certificates

type Config

type Config struct {
	User         string
	Server       string
	Key          string
	KeyPath      string
	Port         string
	Passphrase   string
	Password     string
	Timeout      time.Duration
	JumpHosts    []DefaultConfig
	Ciphers      []string
	KeyExchanges []string
	Fingerprint  string

	// SOCKS5 proxy address (e.g. "127.0.0.1:1080"). Empty means disabled.
	Socks5Proxy string

	// Enable the use of insecure ciphers and key exchange methods.
	// This enables the use of the the following insecure ciphers and key exchange methods:
	// - aes128-cbc
	// - aes192-cbc
	// - aes256-cbc
	// - 3des-cbc
	// - diffie-hellman-group-exchange-sha256
	// - diffie-hellman-group-exchange-sha1
	// Those algorithms are insecure and may allow plaintext data to be recovered by an attacker.
	UseInsecureCipher bool

	// With Logger
	LoggerPrinter func(int, []any)

	// Resumable transfer settings (optional - uses defaults if not set)
	MaxRetries     int           // Maximum reconnection attempts (default: 3)
	RetryDelay     time.Duration // Initial delay between retries (default: 2s)
	EnableChecksum bool          // Enable checksum verification (default: true)
}

Config Contains main authority information. User field should be a name of user on remote server (ex. john in ssh john@example.com). Server field should be a remote machine address (ex. example.com in ssh john@example.com) Key is a path to private key on your local machine. Port is SSH server port on remote machine. Note: easyssh looking for private key in user's home directory (ex. /home/john + Key). Then ensure your Key begins from '/' (ex. /.ssh/id_rsa)

func (*Config) Connect

func (ssh_conf *Config) Connect() (*ssh.Client, error)

Connect to remote server using MakeConfig struct and returns *ssh.Session

func (*Config) ConnectWithRetry

func (c *Config) ConnectWithRetry(policy RetryPolicy) (*ssh.Client, error)

ConnectWithRetry attempts to connect with automatic retry on failure

func (*Config) HealthCheck

func (c *Config) HealthCheck(client *ssh.Client) error

HealthCheck performs a simple health check on the connection

func (Config) HostPort

func (c Config) HostPort() string

func (*Config) Log

func (ssh_conf *Config) Log(calldepth int, args ...any)

func (*Config) NewSFTPFSFromConfig

func (c *Config) NewSFTPFSFromConfig(sshClient *ssh.Client) (fs.FS, error)

NewSFTPFSFromConfig creates a new fs.FS backed by an SFTP connection over the given SSH client. The caller must manage the lifecycle of sshClient and ensure it is not closed while the returned fs.FS is in use.

func (*Config) NewSftpClient

func (ssh_config *Config) NewSftpClient(sshClient *ssh.Client) (*Sftp, error)

func (*Config) Run

func (ssh_conf *Config) Run(command string, timeout ...time.Duration) (outStr string, errStr string, isTimeout bool, err error)

Run command on remote machine and returns its stdout as a string

func (*Config) Scp

func (ssh_conf *Config) Scp(sourceFile, etargetFile string) error

Scp uploads or downloads files between local and remote. If sourceFile exists locally the function performs a local->remote upload (scp -t). If the source does not exist locally it assumes the source is on the remote host and performs a remote->local download using the SFTP client.

func (*Config) ScpWithProgress

func (ssh_conf *Config) ScpWithProgress(sourceFile, etargetFile string, progress ProgressCallback) error

ScpWithProgress uploads or downloads files with progress tracking

func (*Config) SftpDownloadResumable

func (c *Config) SftpDownloadResumable(remoteFile, localFile string) error

SftpDownloadResumable performs SFTP download with in-session resume capability

func (*Config) SftpDownloadResumableWithProgress

func (c *Config) SftpDownloadResumableWithProgress(remoteFile, localFile string, progress ProgressCallback) error

SftpDownloadResumableWithProgress performs SFTP download with progress and auto-retry

func (*Config) SftpUploadResumable

func (c *Config) SftpUploadResumable(sourceFile, targetFile string) error

SftpUploadResumable performs SFTP upload with in-session resume capability

func (*Config) SftpUploadResumableWithProgress

func (c *Config) SftpUploadResumableWithProgress(sourceFile, targetFile string, progress ProgressCallback) error

SftpUploadResumableWithProgress performs SFTP upload with progress and auto-retry

func (*Config) Stream

func (ssh_conf *Config) Stream(client *ssh.Client, command string, timeout ...time.Duration) (<-chan string, <-chan string, <-chan bool, <-chan error, <-chan struct{}, error)

Stream returns one channel that combines the stdout and stderr of the command as it is run on the remote machine, and another that sends true when the command is done. The sessions and channels will then be closed. The sessionClosed channel signals when the session has been fully closed, preventing session accumulation when running multiple commands sequentially.

func (Config) String

func (c Config) String() string

func (Config) Validate

func (c Config) Validate() error

Validate checks that the Config has the minimum required fields set. Returns nil if the configuration is valid, or an error describing the issue.

type ConnectionPool

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

ConnectionPool manages a pool of reusable SSH connections

func NewConnectionPool

func NewConnectionPool(ctx context.Context, config PoolConfig) *ConnectionPool

NewConnectionPool creates a new connection pool

func (*ConnectionPool) Close

func (p *ConnectionPool) Close() error

Close closes all connections and shuts down the pool

func (*ConnectionPool) GetConnection

func (p *ConnectionPool) GetConnection(config *Config) (*ssh.Client, error)

GetConnection gets or creates a connection from the pool

func (*ConnectionPool) GetStats

func (p *ConnectionPool) GetStats() PoolStats

GetStats returns pool statistics

func (*ConnectionPool) ReleaseConnection

func (p *ConnectionPool) ReleaseConnection(client *ssh.Client)

ReleaseConnection returns a connection to the pool

type DefaultConfig

type DefaultConfig struct {
	User         string
	Server       string
	Key          string
	KeyPath      string
	Port         string
	Passphrase   string
	Password     string
	Timeout      time.Duration
	Ciphers      []string
	KeyExchanges []string
	Fingerprint  string

	// SOCKS5 proxy address (e.g. "127.0.0.1:1080"). Empty means disabled.
	Socks5Proxy string

	// Enable the use of insecure ciphers and key exchange methods.
	// This enables the use of the the following insecure ciphers and key exchange methods:
	// - aes128-cbc
	// - aes192-cbc
	// - aes256-cbc
	// - 3des-cbc
	// - diffie-hellman-group-exchange-sha256
	// - diffie-hellman-group-exchange-sha1
	// Those algorithms are insecure and may allow plaintext data to be recovered by an attacker.
	UseInsecureCipher bool
}

DefaultConfig for ssh proxy config

func (DefaultConfig) HostPort

func (d DefaultConfig) HostPort() string

func (DefaultConfig) String

func (d DefaultConfig) String() string

type FSCreate

type FSCreate interface {
	fs.FS
	Create(name string) (io.WriteCloser, error)
}

FSCreate is an optional extension of fs.FS that creates or truncates a file and returns an io.WriteCloser for writing.

type FSMkdirAll

type FSMkdirAll interface {
	fs.FS
	MkdirAll(path string, perm fs.FileMode) error
}

FSMkdirAll is an optional extension of fs.FS that creates a directory and all parent directories.

type FSRemove

type FSRemove interface {
	fs.FS
	Remove(name string) error
}

FSRemove is an optional extension of fs.FS that removes a file or an empty directory.

type FSRemoveAll

type FSRemoveAll interface {
	fs.FS
	RemoveAll(path string) error
}

FSRemoveAll is an optional extension of fs.FS that removes a path and any children it contains.

type FSRename

type FSRename interface {
	fs.FS
	Rename(oldname, newname string) error
}

FSRename is an optional extension of fs.FS that renames (moves) a file or directory.

type FSWriteFile

type FSWriteFile interface {
	fs.FS
	WriteFile(name string, data []byte, perm fs.FileMode) error
}

FSWriteFile is an optional extension of fs.FS that writes data to a file, creating it if it does not exist and truncating it otherwise.

type IPVersion

type IPVersion int

IPVersion represents IP version preference

const (
	IPVersionAny IPVersion = iota
	IPVersionIPv4Only
	IPVersionIPv6Only
	IPVersionPreferIPv6
	IPVersionPreferIPv4
)

type IPv6Config

type IPv6Config struct {
	*Config
	PreferIPv6     bool          // Prefer IPv6 over IPv4 when both available
	IPv6Only       bool          // Only use IPv6 addresses
	IPv4Only       bool          // Only use IPv4 addresses
	ResolveTimeout time.Duration // DNS resolution timeout
}

IPv6Config extends Config with IPv6-specific options

func NewIPv6Config

func NewIPv6Config(config *Config) *IPv6Config

NewIPv6Config creates a new IPv6-enabled config

func (*IPv6Config) ConnectWithIPVersion

func (c *IPv6Config) ConnectWithIPVersion() (net.Conn, error)

ConnectWithIPVersion establishes SSH connection with IP version preference

func (*IPv6Config) SetIPVersion

func (c *IPv6Config) SetIPVersion(version IPVersion)

SetIPVersion configures IP version preference

func (*IPv6Config) ValidateIPv6Config

func (c *IPv6Config) ValidateIPv6Config() error

ValidateIPv6Config validates IPv6 configuration

type IPv6JumpHostConfig

type IPv6JumpHostConfig struct {
	DefaultConfig
	PreferIPv6     bool
	IPv6Only       bool
	IPv4Only       bool
	ResolveTimeout time.Duration
}

IPv6JumpHostConfig extends DefaultConfig for IPv6 jump hosts

func NewIPv6JumpHostConfig

func NewIPv6JumpHostConfig(config DefaultConfig) *IPv6JumpHostConfig

NewIPv6JumpHostConfig creates IPv6-enabled jump host config

type IPv6Tunnel

type IPv6Tunnel struct {
	Tunnel
	BindIPVersion   IPVersion // IP version for bind address
	RemoteIPVersion IPVersion // IP version for remote address
}

IPv6Tunnel extends Tunnel with IPv6 support

func NewIPv6Tunnel

func NewIPv6Tunnel(mode TunMode, bindAddr, dialAddr string) *IPv6Tunnel

NewIPv6Tunnel creates an IPv6-enabled tunnel

type IPv6Utils

type IPv6Utils struct{}

IPv6Utils provides utility functions for IPv6 operations

func (IPv6Utils) GetPreferredAddress

func (u IPv6Utils) GetPreferredAddress(addresses []net.IP, preference IPVersion) net.IP

GetPreferredAddress returns the preferred IP address based on version preference

func (IPv6Utils) IsIPv6Address

func (u IPv6Utils) IsIPv6Address(addr string) bool

IsIPv6Address checks if a string represents an IPv6 address

func (IPv6Utils) NormalizeIPv6Address

func (u IPv6Utils) NormalizeIPv6Address(addr string) string

NormalizeIPv6Address normalizes IPv6 address representation

type KeepAliveConfig

type KeepAliveConfig struct {
	// Interval is the amount of time in seconds to wait before the
	// tunnel client will send a keep-alive message to ensure some minimum
	// traffic on the SSH connection.
	Interval uint

	// CountMax is the maximum number of consecutive failed responses to
	// keep-alive messages the client is willing to tolerate before considering
	// the SSH connection as dead.
	CountMax uint
}

type PoolConfig

type PoolConfig struct {
	MaxConnections      int           // Maximum connections per target
	MaxIdleTime         time.Duration // Maximum idle time before cleanup
	HealthCheckInterval time.Duration // Health check frequency
	ConnectTimeout      time.Duration // Connection establishment timeout
}

PoolConfig configures the connection pool behavior

func DefaultPoolConfig

func DefaultPoolConfig() PoolConfig

DefaultPoolConfig returns sensible defaults for connection pooling

type PoolStats

type PoolStats struct {
	TotalConnections  int
	ActiveConnections int
	IdleConnections   int
	Targets           map[string]int
}

PoolStats provides pool statistics

type PooledConfig

type PooledConfig struct {
	*Config
	// contains filtered or unexported fields
}

PooledConfig extends Config with connection pooling support

func NewPooledConfig

func NewPooledConfig(config *Config, pool *ConnectionPool) *PooledConfig

NewPooledConfig creates a new config with connection pooling

func (*PooledConfig) Connect

func (pc *PooledConfig) Connect() (*ssh.Client, error)

Connect gets a connection from the pool instead of creating a new one

func (*PooledConfig) Run

func (pc *PooledConfig) Run(cmd string, timeout ...time.Duration) (string, string, bool, error)

Run executes a command using a pooled connection

type PooledConnection

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

PooledConnection wraps an SSH client with metadata

type ProgressCallback

type ProgressCallback func(info ProgressInfo) bool

ProgressCallback is called periodically during file transfer operations to report progress. Return false to cancel the transfer.

type ProgressInfo

type ProgressInfo struct {
	// Filename being transferred
	Filename string
	// Total size in bytes (0 if unknown)
	TotalSize int64
	// Bytes transferred so far
	BytesTransferred int64
	// Percentage complete (0-100)
	Percentage float64
	// Transfer speed in bytes per second
	Speed float64
	// Time elapsed since transfer started
	Elapsed time.Duration
	// Estimated time remaining (0 if unknown)
	Remaining time.Duration
}

ProgressInfo contains information about file transfer progress

type RetryPolicy

type RetryPolicy struct {
	MaxRetries      int
	InitialDelay    time.Duration
	MaxDelay        time.Duration
	BackoffMultiper float64
	Jitter          bool
}

RetryPolicy defines retry behavior for connections

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy returns sensible defaults for retry policy

type SSHCertificate

type SSHCertificate struct {
	Certificate     *ssh.Certificate
	PrivateKey      ssh.Signer
	ValidAfter      time.Time
	ValidBefore     time.Time
	Principals      []string
	CertType        uint32
	KeyId           string
	Extensions      map[string]string
	CriticalOptions map[string]string
}

SSHCertificate represents an SSH certificate with metadata

func (*SSHCertificate) GetCertificateInfo

func (cert *SSHCertificate) GetCertificateInfo() map[string]any

GetCertificateInfo returns information about the loaded certificate

func (*SSHCertificate) HasCriticalOption

func (cert *SSHCertificate) HasCriticalOption(option string) bool

HasCriticalOption checks if certificate has a specific critical option

func (*SSHCertificate) HasExtension

func (cert *SSHCertificate) HasExtension(extension string) bool

HasExtension checks if certificate has a specific extension

func (*SSHCertificate) HasPrincipal

func (cert *SSHCertificate) HasPrincipal(principal string) bool

HasPrincipal checks if certificate has a specific principal

func (*SSHCertificate) IsValid

func (cert *SSHCertificate) IsValid() bool

IsValid checks if certificate is currently valid

func (*SSHCertificate) TimeUntilExpiry

func (cert *SSHCertificate) TimeUntilExpiry() time.Duration

TimeUntilExpiry returns time until certificate expires

type Sftp

type Sftp struct {
	*sftp.Client
}

func (*Sftp) Close

func (c *Sftp) Close() error

Explicitly expose commonly used sftp.Client methods to avoid promotion issues with some tooling or linters that may not recognize promoted methods.

func (*Sftp) CopyFromRemote

func (c *Sftp) CopyFromRemote(from, to string) (int64, error)

func (*Sftp) CopyFromRemoteWithProgress

func (c *Sftp) CopyFromRemoteWithProgress(from, to string, progress ProgressCallback) (int64, error)

CopyFromRemoteWithProgress downloads a file from remote server with progress tracking

func (*Sftp) CopyToRemote

func (c *Sftp) CopyToRemote(from, to string) (int64, error)

func (*Sftp) CopyToRemoteWithProgress

func (c *Sftp) CopyToRemoteWithProgress(from, to string, progress ProgressCallback) (int64, error)

CopyToRemoteWithProgress uploads a file to remote server with progress tracking

func (*Sftp) Create

func (c *Sftp) Create(name string) (*sftp.File, error)

func (*Sftp) FS

func (c *Sftp) FS() fs.FS

FS returns an fs.FS backed by this SFTP client. The returned filesystem provides standard Go io/fs interfaces: fs.FS, fs.ReadDirFS, fs.ReadFileFS, fs.StatFS, and fs.SubFS. The caller is responsible for managing the lifecycle of the Sftp client.

func (*Sftp) Open

func (c *Sftp) Open(name string) (*sftp.File, error)

type TunMode

type TunMode string
const (
	TunModeFwd TunMode = "L"
	TunModeRev TunMode = "R"
	TunModeDyn TunMode = "D"
)

type Tunnel

type Tunnel struct {
	SSHConfig     *Config
	Mode          TunMode
	RetryInterval time.Duration
	BindAddr      string
	DialAddr      string
	Logger        *log.Logger
	// contains filtered or unexported fields
}

func (Tunnel) String

func (t Tunnel) String() string

Source Files

  • agent.go
  • async.go
  • certificates.go
  • connect.go
  • internal.go
  • ipv6.go
  • log.go
  • pool.go
  • progress.go
  • reconnect.go
  • resumable_transfer.go
  • scp.go
  • sftp.go
  • sftp_fs.go
  • socks5.go
  • stream.go
  • tunnel.go
  • vezssh.go

Directories

Path Synopsis
examples
agent-forwarding command
SSH Agent Forwarding Example for VezSSH v2.0 This example demonstrates how to use SSH agent forwarding in VezSSH
SSH Agent Forwarding Example for VezSSH v2.0 This example demonstrates how to use SSH agent forwarding in VezSSH
async-operations command
Async Operations Example for VezSSH v2.0 This example demonstrates how to use asynchronous operations in VezSSH
Async Operations Example for VezSSH v2.0 This example demonstrates how to use asynchronous operations in VezSSH
certificates command
SSH Certificate Authentication Example for VezSSH v2.0 This example demonstrates how to use SSH certificate authentication in VezSSH
SSH Certificate Authentication Example for VezSSH v2.0 This example demonstrates how to use SSH certificate authentication in VezSSH
connection-pool command
Connection Pool Example for VezSSH v2.0 This example demonstrates how to use connection pooling for efficient SSH connection management
Connection Pool Example for VezSSH v2.0 This example demonstrates how to use connection pooling for efficient SSH connection management
ipv6-support command
IPv6 Support Example for VezSSH v2.0 This example demonstrates how to use IPv6 capabilities in VezSSH
IPv6 Support Example for VezSSH v2.0 This example demonstrates how to use IPv6 capabilities in VezSSH
progress-demo command

Jump to

Keyboard shortcuts

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