Documentation
¶
Overview ¶
Package sshcommands provides SSH/SFTP operations (upload, list, delete, download, fetch host key) with parameter-based API, no config dependency.
Index ¶
- Constants
- Variables
- func AppendKnownHostsLine(knownHostsPath, hostToken, keyLine string, log Logger) (err error)
- func AppendServerHostKey(opts *Opts, knownHostsPath string, log Logger) (written bool, err error)
- func Delete(opts *Opts, remoteDir string, names []string, log Logger) error
- func DialKnownHosts(opts *Opts, kh KnownHostsOptions, log Logger) (*ssh.Client, error)
- func DialWithHostKeyCallback(opts *Opts, hostKeyCallback ssh.HostKeyCallback, log Logger) (*ssh.Client, error)
- func Download(opts *Opts, pattern, destDir, remoteDir, aesPassword string, log Logger) ([]string, error)
- func DownloadWithOptions(opts *Opts, pattern, destDir, remoteDir, aesPassword string, ...) ([]string, error)
- func FetchServerHostKey(opts *Opts) (keyLine string, err error)
- func FormatKnownHostsHostToken(host string, port int) string
- func HostKeyAlreadyPresent(currentValue, newKeyLine string) (bool, error)
- func MkdirAllRemote(client *ssh.Client, remotePath string, log Logger) error
- func NewSFTPClient(opts *Opts, log Logger) (*sftp.Client, *ssh.Client, error)
- func Sync(opts *Opts, localFiles []LocalFile, remoteDir, aesPassword string, log Logger) error
- func UploadFileIfNewer(client *ssh.Client, localPath, remotePath string, log Logger) error
- func ValidDownloadPattern(pattern string) bool
- func ValidRemoteFileName(name string) bool
- type DownloadOptions
- type KnownHostsOptions
- type LocalFile
- type Logger
- type Opts
- type RemoteEntry
Constants ¶
const ( DefaultKeepAliveInterval = 15 * time.Second DefaultKeepAliveMaxMissed = 3 )
Keepalive defaults: a request every DefaultKeepAliveInterval; the connection is closed after DefaultKeepAliveMaxMissed unanswered requests.
const DefaultSSHPort = 22
DefaultSSHPort is used when Opts.Port is zero.
const DefaultSSHTimeout = 30 * time.Second
DefaultSSHTimeout is used when Opts.Timeout is zero.
const EncryptionOverhead = headerLen + macLen
EncryptionOverhead is the number of bytes added to an encrypted stream (header plus MAC).
Variables ¶
var ( // Version is the semantic-like version string of the library. // Format: Major.Minor.Patch.Build. Version = "1.1.0.6" // BuildTime is the timestamp of the build, typically injected via -ldflags // at build time. BuildTime = "2026-11-04 12:24:43" )
var ErrDecryptIntegrity = errors.New("encrypted data failed integrity check: wrong AES password, corrupted or renamed file")
ErrDecryptIntegrity is returned when an encrypted file fails its integrity check (wrong AES password, corrupted/modified data or renamed file).
var ErrDownloadTooLarge = errors.New("remote file exceeds DownloadOptions.MaxSize")
ErrDownloadTooLarge is returned when a remote file exceeds DownloadOptions.MaxSize.
var ErrNotEncrypted = errors.New("remote file is not encrypted in the current format (legacy files need DownloadOptions.AllowLegacyDecryption)")
ErrNotEncrypted is returned by Download when an AES password is given but the remote file is not in the current encrypted format.
var ErrRemoteNotConfigured = errors.New("remote not configured: set Host in Opts")
ErrRemoteNotConfigured is returned by all operations when Opts.Host is empty. Callers that treat the remote as optional can check it with errors.Is.
Functions ¶
func AppendKnownHostsLine ¶
AppendKnownHostsLine appends a host token and key line to a known_hosts file. The token must name exactly one host (see FormatKnownHostsHostToken); the key is written as "key-type base64". Parent directories are created as needed. A missing newline at the end of the existing file is added first.
func AppendServerHostKey ¶
AppendServerHostKey fetches the server host key (without sending credentials) and appends it to knownHostsPath when the file does not know the host yet. A host that is already listed (with any key) is left unchanged and not contacted; a changed key then fails at connect time as a mismatch. Returns written=true when a new line was added.
func Delete ¶
Delete removes the given file names from remoteDir. All names are validated before connecting; names containing path components or ".." are rejected and nothing is deleted. Failed removals are collected and returned together (errors.Join) after all names were tried.
func DialKnownHosts ¶
DialKnownHosts connects using KnownHostsOptions.Path for host key verification. opts.HostKey is ignored. When FetchHostKey is set and the file is missing or does not know the host yet, the server key is fetched (without sending credentials) and appended. With TrustOnMismatch a changed key replaces the host's previous entries (development only, see KnownHostsOptions).
func DialWithHostKeyCallback ¶
func DialWithHostKeyCallback(opts *Opts, hostKeyCallback ssh.HostKeyCallback, log Logger) (*ssh.Client, error)
DialWithHostKeyCallback connects using a custom host key callback instead of opts.HostKey. opts.HostKey is ignored.
func Download ¶
func Download(opts *Opts, pattern, destDir, remoteDir, aesPassword string, log Logger) ([]string, error)
Download downloads files matching pattern from remoteDir into destDir with default DownloadOptions. See DownloadWithOptions.
func DownloadWithOptions ¶ added in v1.1.0
func DownloadWithOptions(opts *Opts, pattern, destDir, remoteDir, aesPassword string, dopts DownloadOptions, log Logger) ([]string, error)
DownloadWithOptions downloads files matching pattern from remoteDir into destDir (required). Pattern may be a literal filename or contain wildcards (*, ?); no path components. aesPassword empty = no decryption (surrounding whitespace is ignored); with a password every file must be encrypted in the current format (ErrNotEncrypted otherwise, see AllowLegacyDecryption). Existing local files are never overwritten: the file is saved as "<name>.lokal" (or "<name>.lokal.N"). Returns the list of local paths written.
func FetchServerHostKey ¶
FetchServerHostKey connects to the SSH server, captures its host key and returns it as a single line ("key-type base64"). The handshake is aborted right after the key exchange, so no credentials are sent and Opts.User, KeyFile and Password are not needed. The key is NOT verified; use it only for initial setup (trust on first use).
func FormatKnownHostsHostToken ¶
FormatKnownHostsHostToken returns the host token for a known_hosts entry.
func HostKeyAlreadyPresent ¶
HostKeyAlreadyPresent returns true if newKeyLine is already among the keys in currentValue (inline " || "-separated keys or path to a known_hosts file). The check ignores host names; revoked (@revoked) and @cert-authority lines never count as present. Use a host-aware check for known_hosts files where the host matters (AppendServerHostKey does).
func MkdirAllRemote ¶
MkdirAllRemote creates remotePath and any missing parent directories via SFTP.
func NewSFTPClient ¶
NewSFTPClient returns an SFTP client; caller must Close() both clients.
func Sync ¶
Sync uploads local files that are missing, newer or of a different size on the remote, and deletes remote files that are not in localFiles (including leftovers of aborted uploads). remoteDir is created if needed. aesPassword empty = no encryption (surrounding whitespace is ignored).
All names are validated before connecting. An empty localFiles list is rejected because it would delete every file in remoteDir; use Delete to remove files explicitly.
func UploadFileIfNewer ¶
UploadFileIfNewer uploads localPath to remotePath when the remote file is missing, has a different size, or the local file is newer (compared in whole seconds). Remote parent directories are created as needed, the upload goes to a temporary name first and the remote mtime is set to the local mtime.
func ValidDownloadPattern ¶
ValidDownloadPattern returns false if pattern contains path components (no /, \, ..).
func ValidRemoteFileName ¶ added in v1.1.0
ValidRemoteFileName returns false if name is empty or ".", contains path components, "..", or control characters (0x00-0x1f, 0x7f). Use for any remote or local filename that is joined to a base directory.
Types ¶
type DownloadOptions ¶ added in v1.1.0
type DownloadOptions struct {
// AllowLegacyDecryption decrypts files without the current format header
// in the legacy format (written before 0.3.0, no integrity check). Only
// enable it to migrate old backups: an attacker with write access to the
// server can then modify such files undetected.
AllowLegacyDecryption bool
// MaxSize limits the size of each remote file in bytes; 0 = unlimited.
MaxSize int64
}
DownloadOptions controls DownloadWithOptions. The zero value is the secure default used by Download.
type KnownHostsOptions ¶
type KnownHostsOptions struct {
// Path to the known_hosts file (required).
Path string
// FetchHostKey captures the server's host key (without authenticating) and
// appends it to Path when the file is missing or does not know the host yet
// (trust on first use).
FetchHostKey bool
// TrustOnMismatch on host key mismatch fetches the current server key,
// appends it to Path, and retries the connection once. This disables the
// protection against man-in-the-middle attacks for changed keys.
TrustOnMismatch bool
}
KnownHostsOptions controls SSH connections that verify the server via an OpenSSH known_hosts file. opts.HostKey is ignored; Path is used instead.
type Opts ¶
type Opts struct {
Host string // SSH host name or IP address (IPv6 without brackets)
Port int // 0 => DefaultSSHPort (22)
User string // SSH user (required)
KeyFile string // path to private key (optional)
KeyPassphrase string // passphrase of an encrypted KeyFile (optional)
Password string // plaintext password (optional); at least KeyFile or Password required
HostKey string // path to known_hosts file or inline key(s), separated by " || "
Timeout time.Duration // limit for TCP connect, SSH handshake and SFTP start; 0 => DefaultSSHTimeout (30s)
// KeepAliveInterval is the interval of SSH keepalive requests that detect
// a hanging server; 0 => DefaultKeepAliveInterval, negative => disabled.
KeepAliveInterval time.Duration
// KeepAliveMaxMissed unanswered keepalives close the connection;
// 0 => DefaultKeepAliveMaxMissed.
KeepAliveMaxMissed int
}
Opts holds SSH/SFTP connection parameters.
type RemoteEntry ¶
RemoteEntry describes a remote file (name, modtime, size).