ssh

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 26 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ssh establishes authenticated SSH PTY shell Channels. Session, rather than Transport, owns output history and shared access.

Index

Constants

This section is empty.

Variables

View Source
var ErrKeepAliveTimeout = errors.New("SSH keepalive response timed out")

ErrKeepAliveTimeout reports a peer that did not answer an SSH liveness probe.

View Source
var ErrWriteTimeout = errors.New("SSH write timed out; connection closed")

ErrWriteTimeout reports shell input or resizing that exceeded WriteTimeout. The connection is closed because some bytes may already have been delivered.

Functions

func ValidFileName

func ValidFileName(name string) bool

ValidFileName accepts one portable path component, rejecting traversal, Windows drive/stream/device spellings, and protocol control characters.

Types

type Config

type Config struct {
	User           string
	Host           string
	Port           int
	PrivateKeyPath string
	// PrivateKeyPaths adds candidates after PrivateKeyPath, in order. Duplicate
	// paths are tried once. Invalid/missing files fail before network access.
	PrivateKeyPaths []string
	KnownHostsPath  string
	Timeout         time.Duration
	Term            string
	Columns         int
	Rows            int

	// KeepAliveInterval enables periodic authenticated probes after setup.
	// Zero disables probes. KeepAliveCountMax defaults to 3 and bounds the
	// response wait to interval * count; negative replies count as responses.
	KeepAliveInterval time.Duration
	KeepAliveCountMax int
	// WriteTimeout bounds each shell Write and Resize, including flow control.
	// Zero disables it. Expiry closes the connection; input is never replayed.
	WriteTimeout time.Duration

	// Password supplies a fresh password only when the server offers password
	// authentication and any configured key did not succeed. Up to three attempts
	// are made. Ownership of the returned bytes transfers to Transport, which
	// clears them after conversion for the backend. Passwords are never persisted.
	// The callback must honor ctx cancellation and must not read shared shell input.
	Password func(ctx context.Context) ([]byte, error)

	// KeyPassphrase unlocks an encrypted identity after host verification.
	// The callback must honor ctx; Transport clears returned bytes. Wrong
	// passphrases allow up to three attempts. Cancellation aborts authentication.
	// Decrypted signers belong only to one connection and are not persisted.
	KeyPassphrase func(ctx context.Context, path string) ([]byte, error)

	// ConfirmHostKey may approve an unknown server key for persistence. It is
	// never called for changed or revoked keys. Nil means strict rejection.
	// The callback must honor ctx; adapters own presentation. Network setup time
	// excludes callbacks, but the caller's cancellation/deadline still applies.
	ConfirmHostKey func(ctx context.Context, key HostKey) (bool, error)
}

Config describes one SSH shell connection using library-independent values. PrivateKeyPath optionally identifies the first private key; PrivateKeyPaths adds ordered candidates. Encrypted keys use KeyPassphrase. KnownHostsPath identifies the required OpenSSH host-key database. Zero Port, Timeout, Term, Columns, and Rows select 22, 10 seconds, xterm-256color, 80, and 24 respectively. Configuration is not persisted by this package.

type FileInfo

type FileInfo struct {
	Name     string      `json:"name"`
	Size     int64       `json:"size"`
	Mode     fs.FileMode `json:"mode"`
	Modified time.Time   `json:"modified"`
}

FileInfo describes a remote entry without exposing SSH/SFTP backend types.

type Files

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

Files owns a dedicated SSH connection for file operations, never a PTY or terminal Session. Operations are caller-serialized. Close may run concurrently to interrupt blocked I/O; cancellation of the opening context also closes the connection. Call Close even after cancellation to join owned client workers.

func (*Files) Close

func (f *Files) Close() error

Close interrupts active file operations and releases the dedicated connection. It is idempotent and safe to call concurrently with cancellation or I/O.

func (*Files) Create

func (f *Files) Create(path string, overwrite bool) (io.WriteCloser, error)

Create creates a remote regular file, rejecting an existing path unless overwrite is explicitly requested. A failed transfer may leave partial bytes.

func (*Files) DownloadSCP

func (f *Files) DownloadSCP(source string, recursive bool, receive func(SCPEntry, io.Reader) error, verify func(SCPEntry) error) (files int64, err error)

DownloadSCP delivers validated entries to receive synchronously. A file reader is limited to its declared size and must be fully consumed before returning. Directories have nil readers. The caller owns local destination policy and containment. Duplicate/traversal names, excessive nesting, and extra roots fail. files counts regular files only after receive succeeds and both final file acknowledgements succeed. Earlier completed files remain counted on error; the operation still requires successful framing and remote command exit. When verify is nonnil, it runs after the acknowledgements and must succeed before counting the file. Callbacks are serialized, including across files.

func (*Files) List

func (f *Files) List(path string) ([]FileInfo, error)

List returns the immediate children of a remote directory, including symlinks.

func (*Files) Mkdir

func (f *Files) Mkdir(path string) error

Mkdir creates exactly one remote directory; its parent must already exist.

func (*Files) Open

func (f *Files) Open(path string) (io.ReadCloser, error)

Open reads a remote file. The caller must close the handle before Files.Close.

func (*Files) Remove

func (f *Files) Remove(path string, directory bool) error

Remove removes a file/symlink, or an empty directory when directory is true. Recursive deletion is deliberately not implicit in either operation.

func (*Files) Rename

func (f *Files) Rename(oldPath, newPath string, overwrite bool) error

Rename moves an entry. Replacement requires the server's POSIX rename extension; no delete-then-rename fallback risks destroying the destination.

func (*Files) RequirePOSIXRename

func (f *Files) RequirePOSIXRename() error

RequirePOSIXRename checks for the server extension needed to replace a remote file without a delete-first fallback. Call before staging an upload.

func (*Files) RequireSHA256

func (f *Files) RequireSHA256() error

RequireSHA256 checks the fixed remote hashing utility before an SCP transfer can modify its destination. It requires a POSIX shell with sha256sum in PATH.

func (*Files) SCPUploadDestination

func (f *Files) SCPUploadDestination(destination, name string) (string, error)

SCPUploadDestination resolves SCP's existing-directory rule without cleaning literal remote path components. Concurrent remote namespace changes are not locked; the later digest must still match the actual file at this path.

func (*Files) SHA256

func (f *Files) SHA256(remote string) (string, error)

SHA256 hashes a remote file through a fixed, quoted command on the dedicated SCP connection. It never uses a terminal Session or requests a PTY. The connection's operation context interrupts command setup, output, and exit.

func (*Files) Stat

func (f *Files) Stat(path string) (FileInfo, error)

Stat reports an entry itself, without following its final symlink.

func (*Files) UploadSCP

func (f *Files) UploadSCP(source fs.FS, name, destination string, recursive, overwrite bool, progress func(string, int64, int64) error, verify func(SCPEntry, string) error) (files, totalBytes int64, err error)

UploadSCP sends a regular file or directory tree using the legacy SCP wire protocol and a remote POSIX scp command. Names are literal, not shell globs. Source must be a confined filesystem; symlink/special entries are rejected. overwrite=false adds a remote existence guard, not an atomic reservation. Progress reports zero bytes before each file, including an empty file; an error aborts transfer. Payload progress precedes the final acknowledgement. When verify is nonnil, it receives the source payload SHA-256 after the peer's final acknowledgement and must succeed before the file is counted.

type HostKey

type HostKey struct {
	Address     string
	Algorithm   string
	Fingerprint string
}

HostKey is the non-secret identity displayed for an unknown SSH server. Address uses OpenSSH's normalized host/port form; Fingerprint uses SHA256. Adapters approve this identity, never supply replacement key material.

type SCPEntry

type SCPEntry struct {
	Path string
	Size int64
	Mode fs.FileMode
}

SCPEntry is one validated relative path in a legacy SCP transfer. The first component is the requested source basename, never an arbitrary server path.

type StageError

type StageError struct {
	Stage string
	Err   error
}

StageError identifies the failed SSH operation without exposing credentials. Stage is identity, dns, connect, host-key, authentication, handshake, shell, subsystem, transfer, or liveness. Unwrap preserves cancellation and underlying errors.

func (*StageError) Error

func (e *StageError) Error() string

Error formats the stage and cause, distinguishing cancellation and timeout.

func (*StageError) Unwrap

func (e *StageError) Unwrap() error

Unwrap exposes the original error for errors.Is and errors.As.

type Transport

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

Transport retains validated connection settings, never a live stream. Each successful Connect transfers an independent SSH connection to a Channel.

func New

func New(config Config) (*Transport, error)

New validates config and loads authentication and host trust without opening a network connection. It retains a private snapshot of the parsed credentials; callers exchange only paths and settings, never backend-specific objects. Changes to either file require constructing a new Transport. A missing trust file is allowed only with an explicit unknown-host confirmation provider.

func (*Transport) Connect

func (t *Transport) Connect(ctx context.Context) (_ channel.Channel, err error)

Connect authenticates, requests a PTY, and starts an interactive shell. ctx bounds setup; Config.Timeout bounds network work, excluding time spent in interaction callbacks. Cancellation releases every partial resource. After success, ctx no longer controls the Channel: only Channel.Close owns its lifetime. Concurrent Connect calls require concurrency-safe callbacks.

func (*Transport) Endpoint

func (t *Transport) Endpoint() string

Endpoint returns the validated user@host:port Session-reuse key. IPv6 hosts are bracketed, and credentials are never included.

func (*Transport) OpenFiles

func (t *Transport) OpenFiles(ctx context.Context, protocol string) (*Files, error)

OpenFiles authenticates a dedicated file connection. protocol is "sftp" or "scp". SFTP requests a subsystem; SCP opens an exec channel per transfer. Config.Timeout bounds setup while ctx bounds the complete file-client lifetime. The returned connection is not registered with the shared Session Manager.

Jump to

Keyboard shortcuts

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