sshx

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2025 License: MIT Imports: 16 Imported by: 0

README

sshx

A SSH client library for Go with support for command execution, file uploads, and template rendering.

Features

  • Command execution: Execute command on a remote machines
  • File Uploads: Upload files with permissions and ownership control
  • Template Support: Render and upload Go templates to remote machines

Quick Start

package main

import (
    "log"
    "github.com/eznix86/sshx"
)

func main() {
    // Create a machine
    m := sshx.NewMachine("user@host:22")
    defer m.Close()

    // Run a command
    output, err := m.Run("uptime")
    if err != nil {
        log.Fatal(err)
    }
    log.Println(output)

    // Upload a file
    err = m.Upload("local.txt", "/remote/path.txt")
    if err != nil {
        log.Fatal(err)
    }
}

Configuration Options

Connection Options
  • WithTimeout(duration) - Set connection timeout
  • WithKnownHosts(path) - Set known_hosts file path
  • WithAutoKnownHosts() - Auto-load ~/.ssh/known_hosts
Authentication Options
  • WithAuth(method) - Use custom SSH auth method
  • WithKeyPath(path) - Load specific SSH key
  • WithDefaultKeys() - Load default keys from ~/.ssh/
  • WithAgent() - Use SSH agent

Usage

Upload with Metadata
err := m.UploadWithMeta("app.conf", "/etc/app.conf", sshx.FileMeta{
    Perm:  0644,
    Owner: "www-data",
    Group: "www-data",
})
Template Upload
data := struct {
    Port int
    Host string
}{Port: 8080, Host: "localhost"}

err := m.UploadTemplate("/etc/config.conf",
    sshx.WithTemplateString("Server={{.Host}}:{{.Port}}", data),
    sshx.WithPermission(0644),
    sshx.WithOwner("root", "root"),
)
Custom Authentication
m := sshx.NewMachine("host",
    sshx.WithKeyPath("/path/to/private/key"),
    sshx.WithKnownHosts("/custom/known_hosts"),
    sshx.WithTimeout(30*time.Second),
)

License

MIT License - see LICENSE file for details.

Documentation

Overview

Package sshx provides a high-level SSH client library for executing commands and managing files on remote machines.

Basic Usage

Create a machine and run commands:

m := sshx.NewMachine("user@host:22")
output, err := m.Run("ls -la")
if err != nil {
    log.Fatal(err)
}
fmt.Println(output)

Configuration

Configure the machine with functional options:

m := sshx.NewMachine("host",
    sshx.WithTimeout(30*time.Second),
    sshx.WithKeyPath("/path/to/key"),
    sshx.WithAutoKnownHosts(),
)

File Operations

Upload files with metadata:

err := m.UploadWithMeta("local.txt", "/remote/path.txt", sshx.FileMeta{
    Perm:  0644,
    Owner: "www-data",
    Group: "www-data",
})

Template Upload

Render and upload templates:

err := m.UploadTemplate("/etc/config.conf",
    sshx.WithTemplateString("Server={{.Host}}", data),
    sshx.WithPermission(0644),
    sshx.WithOwner("root", "root"),
)

Cleanup

Always close connections when done:

defer m.Close()

Index

Constants

View Source
const (
	// Default file permissions
	DefaultFileMode os.FileMode = 0644
	DefaultDirMode  os.FileMode = 0755

	// Default SSH connection settings
	DefaultTimeout = 10 * time.Second
	DefaultSSHPort = 22
	DefaultUser    = "root"
)

Variables

This section is empty.

Functions

func LoadDefaultKeyMethods

func LoadDefaultKeyMethods() []ssh.AuthMethod

LoadDefaultKeyMethods loads default SSH keys from ~/.ssh/ Attempts to load id_ed25519, id_rsa, and id_ecdsa in that order

func LoadSSHAgent

func LoadSSHAgent() (ssh.AuthMethod, error)

LoadSSHAgent connects to the SSH agent and returns an auth method

func ParseTarget

func ParseTarget(input string) (string, string, int)

ParseTarget parses a target string in the format [user@]host[:port]

Types

type FileMeta

type FileMeta struct {
	Perm  os.FileMode
	Owner string
	Group string
}

FileMeta contains metadata for uploaded files

type Machine

type Machine struct {
	Host string
	User string
	Port int

	AuthMethods []ssh.AuthMethod
	KnownHosts  string
	Timeout     time.Duration
	// contains filtered or unexported fields
}

Machine represents a remote SSH machine with connection capabilities

func NewMachine

func NewMachine(target string, opts ...Option) *Machine

NewMachine creates a new Machine instance with the given target and options Target format: [user@]host[:port]

func (*Machine) Close

func (m *Machine) Close() error

Close closes the SFTP and SSH connections

func (*Machine) Run

func (m *Machine) Run(cmd string) (string, error)

Run executes a command on the remote machine and returns the combined output

func (*Machine) Upload

func (m *Machine) Upload(local, remote string) error

Upload uploads a local file to a remote path with default permissions

func (*Machine) UploadTemplate

func (m *Machine) UploadTemplate(remote string, opts ...TemplateOption) error

UploadTemplate renders a template and uploads it to a remote path The template can be provided via WithTemplateString, WithTemplateBytes, or WithTemplateFS

func (*Machine) UploadWithMeta

func (m *Machine) UploadWithMeta(local, remote string, meta FileMeta) error

UploadWithMeta uploads a local file to a remote path with specified metadata

type Option

type Option func(*Machine)

Option is a functional option for configuring a Machine

func WithAgent

func WithAgent() Option

WithAgent uses the SSH agent for authentication

func WithAuth

func WithAuth(a ssh.AuthMethod) Option

WithAuth sets a custom SSH authentication method

func WithAutoKnownHosts

func WithAutoKnownHosts() Option

WithAutoKnownHosts automatically loads the user's known_hosts file

func WithDefaultKeys

func WithDefaultKeys() Option

WithDefaultKeys loads default SSH keys from ~/.ssh/

func WithKeyPath

func WithKeyPath(path string) Option

WithKeyPath loads an SSH key from the specified path

func WithKnownHosts

func WithKnownHosts(path string) Option

WithKnownHosts sets the path to the known_hosts file

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the SSH connection timeout

type TemplateOption

type TemplateOption func(*TemplatePayload)

TemplateOption is a functional option for configuring template rendering

func WithOwner

func WithOwner(user, group string) TemplateOption

func WithPermission

func WithPermission(perm os.FileMode) TemplateOption

func WithTemplateBytes

func WithTemplateBytes(b []byte, data any) TemplateOption

func WithTemplateFS

func WithTemplateFS(fsys fs.FS, path string, data any) TemplateOption

func WithTemplateString

func WithTemplateString(s string, data any) TemplateOption

type TemplatePayload

type TemplatePayload struct {
	Content  string
	FromFile string
	Data     any

	ReadFS fs.FS
	FSPath string

	Perm  os.FileMode
	Owner string
	Group string
}

TemplatePayload contains all the data needed to render and upload a template

Jump to

Keyboard shortcuts

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