Documentation
¶
Overview ¶
Package ssh provides an enterprise-grade SSH tunneling, command execution, and file transfer client.
Index ¶
- Constants
- Variables
- func AddKnownHost(host string, remote net.Addr, key ssh.PublicKey, knownFile string) error
- func CheckKnownHost(host string, remote net.Addr, key ssh.PublicKey, knownFile string) (bool, error)
- func DefaultKnownHosts() (ssh.HostKeyCallback, error)
- func DefaultKnownHostsPath() (string, error)
- func Dial(ctx context.Context, c *Client, config *ssh.ClientConfig) error
- func EnsureKnownHosts(file string) (ssh.HostKeyCallback, error)
- func KnownHosts(file string) (ssh.HostKeyCallback, error)
- func ParseCertKey(certBytes, keyBytes []byte, passphrase string) (ssh.Signer, error)
- func ParseCertKeyFile(certFile, keyFile, passphrase string) (ssh.Signer, error)
- func ParseKey(privateKey []byte, passphrase string) (ssh.Signer, error)
- func ParseKeyFile(prvFile, passphrase string) (ssh.Signer, error)
- type Client
- func (c *Client) Close() error
- func (c *Client) Command(ctx context.Context, name string, args ...string) (*Cmd, error)
- func (c *Client) DialContext(ctx context.Context, network, targetAddr string) (net.Conn, error)
- func (c *Client) DialUnix(ctx context.Context, remoteSocketPath string) (net.Conn, error)
- func (c *Client) Download(remotePath, localPath string) error
- func (c *Client) DownloadParallel(ctx context.Context, remotePath, localPath string, workers int, ...) error
- func (c *Client) GetSftp(opts ...pkgsftp.ClientOption) (*pkgsftp.Client, error)
- func (c *Client) ListenSOCKS5(ctx context.Context, localAddr string) (net.Listener, error)
- func (c *Client) NewSftp(opts ...pkgsftp.ClientOption) (*pkgsftp.Client, error)
- func (c *Client) Run(ctx context.Context, cmdStr string) ([]byte, error)
- func (c *Client) Scp(ctx context.Context, localFilePath, remoteFilePath string) error
- func (c *Client) Script(ctx context.Context, r io.Reader, opts ...CmdOption) (*Cmd, error)
- func (c *Client) ScriptFile(ctx context.Context, localPath string, opts ...CmdOption) (*Cmd, error)
- func (c *Client) Stream(ctx context.Context, command string, timeout time.Duration) (<-chan string, <-chan string, <-chan bool, <-chan error, error)
- func (c *Client) Upload(localPath, remotePath string) error
- func (c *Client) UploadParallel(ctx context.Context, localPath, remotePath string, workers int, ...) error
- func (c *Client) WriteFile(ctx context.Context, r io.Reader, size int64, remoteFilePath string) error
- type Cmd
- type CmdOption
- type ContextDialer
- type HostConfig
- type Option
- func WithAgent(conn net.Conn) Option
- func WithAgentSocket(socket string) Option
- func WithAuth(method ssh.AuthMethod) Option
- func WithBannerCallback(cb ssh.BannerCallback) Option
- func WithCert(certBytes, keyBytes []byte, passphrase string) Option
- func WithCertFile(certFile, keyFile, passphrase string) Option
- func WithCertSigner(signer ssh.Signer) Option
- func WithCiphers(ciphers []string) Option
- func WithConfig(fn func(*ssh.ClientConfig) error) Option
- func WithDefaultAgent() Option
- func WithDialer(dialer ContextDialer) Option
- func WithEnsureKnownHosts(path string) Option
- func WithFingerprint(fingerprint string) Option
- func WithHighPerformanceDefaults() Option
- func WithHostKeyAlgorithms(algorithms []string) Option
- func WithHostKeyCallback(cb ssh.HostKeyCallback) Option
- func WithInsecureIgnoreHostKey() Option
- func WithJump(jumpClient *Client) Option
- func WithKey(pemBytes []byte, passphrase string) Option
- func WithKeyExchanges(kex []string) Option
- func WithKeyFile(keyFile, passphrase string) Option
- func WithKeyboardInteractive(handler func(user, instruction, question string, echo bool) (string, error)) Option
- func WithKnownHosts(path string) Option
- func WithLegacyCiphers() Option
- func WithMaxPacketSize(size uint32) Option
- func WithPassword(password string) Option
- func WithPort(port uint) Option
- func WithProxy(socks5URL string) Option
- func WithPtyTerminal(term string, width, height int) Option
- func WithRequestPty(enabled bool) Option
- func WithSigner(signer ssh.Signer) Option
- func WithTimeout(d time.Duration) Option
- func WithWindowSize(size uint32) Option
- type SSHConfig
Constants ¶
const ( // DefaultWindowSize specifies the default initial SSH channel window size (16MB). DefaultWindowSize uint32 = 16 * 1024 * 1024 // DefaultMaxPacketSize specifies the default maximum SSH packet size (64KB). DefaultMaxPacketSize uint32 = 64 * 1024 )
Variables ¶
var ( // ErrSSHDialFailed is returned when connecting or authenticating with an SSH server fails. ErrSSHDialFailed = errors.New("aoni/ssh/client: connection or authentication failed") // ErrSSHClosed is returned when attempting an operation on an inactive SSH client. ErrSSHClosed = errors.New("aoni/ssh/client: session is closed") // ErrInvalidPrivateKey is returned when parsing an invalid or encrypted PEM private key fails. ErrInvalidPrivateKey = errors.New("aoni/ssh/client: invalid or encrypted private key") // ErrInvalidCertificate is returned when parsing or validating an OpenSSH certificate fails. ErrInvalidCertificate = errors.New("aoni/ssh/client: invalid or corrupted ssh certificate") // ErrHostKeyMismatch is returned when a host key does not match the entry in known_hosts. ErrHostKeyMismatch = errors.New("aoni/ssh/client: host key mismatch detected") // ErrHostNotFound is returned when a host key is missing from the known_hosts file. ErrHostNotFound = errors.New("aoni/ssh/client: host not found in known_hosts") // ErrCommandInitFailed is returned when environment variables or session options fail to apply. ErrCommandInitFailed = errors.New("aoni/ssh/client: command initialization failed") // ErrProxyAndJumpConflict is returned when attempting to set both a SOCKS5 proxy and an SSH jump host on the same client. ErrProxyAndJumpConflict = errors.New("aoni/ssh/client: cannot combine proxy and jump host on the same client level") // ErrFingerprintMismatch is returned when the remote host key fingerprint does not match the expected SHA256 pin. ErrFingerprintMismatch = errors.New("aoni/ssh/client: host key fingerprint mismatch") // ErrPtyRequestFailed is returned when the server rejects a pseudo-terminal (PTY) allocation request. ErrPtyRequestFailed = errors.New("aoni/ssh/client: failed to request pseudo-terminal") )
Functions ¶
func AddKnownHost ¶
AddKnownHost appends a host key entry to knownFile and invalidates the internal callback cache.
func CheckKnownHost ¶
func CheckKnownHost(host string, remote net.Addr, key ssh.PublicKey, knownFile string) (bool, error)
CheckKnownHost verifies if host exists in knownFile using cached host key callbacks. Returns (true, nil) if matched, (true, ErrHostKeyMismatch) on key mismatch, or (false, ErrHostNotFound) if absent.
func DefaultKnownHosts ¶
func DefaultKnownHosts() (ssh.HostKeyCallback, error)
DefaultKnownHosts returns a host key callback using the default user known_hosts file path.
func DefaultKnownHostsPath ¶
DefaultKnownHostsPath returns the standard ~/.ssh/known_hosts path.
func Dial ¶
Dial connects client to the remote target host using configured options, proxies, or jump hosts.
func EnsureKnownHosts ¶
func EnsureKnownHosts(file string) (ssh.HostKeyCallback, error)
EnsureKnownHosts returns a host key callback, creating the file and parent directory if missing.
func KnownHosts ¶
func KnownHosts(file string) (ssh.HostKeyCallback, error)
KnownHosts returns a thread-safe, cached host key callback targeting an existing known_hosts file path. Debounces os.Stat calls using a 1-second interval to eliminate disk I/O syscall overhead.
func ParseCertKey ¶
ParseCertKey parses a private key and an OpenSSH certificate payload, returning a cert-backed ssh.Signer ready for SSH client authentication.
func ParseCertKeyFile ¶
ParseCertKeyFile loads and parses a cert-backed ssh.Signer from file paths.
Types ¶
type Client ¶
type Client struct {
*ssh.Client
User string
Addr string
Port uint
ProxyURL string
Jump *Client
Dialer ContextDialer
RequestPty bool
PtyTerm string
PtyWidth int
PtyHeight int
WindowSize uint32
MaxPacketSize uint32
// contains filtered or unexported fields
}
Client represents an SSH client session routed through aoni's L4 network transport pipeline.
func NewClientFromConfig ¶
NewClientFromConfig creates an SSH Client loading options automatically from ~/.ssh/config for alias.
func (*Client) Close ¶
Close terminates the keep-alive worker, active SFTP client, and underlying SSH connection.
func (*Client) DialContext ¶
DialContext establishes a routed TCP connection through the remote SSH tunnel.
func (*Client) DialUnix ¶
DialUnix establishes a streamlocal UNIX domain socket connection on the remote host via SSH.
func (*Client) DownloadParallel ¶
func (c *Client) DownloadParallel( ctx context.Context, remotePath, localPath string, workers int, chunkSize int64, ) error
DownloadParallel downloads a remote file to localPath over SFTP using multiple worker threads.
func (*Client) GetSftp ¶
GetSftp returns a thread-safe, cached SFTP client instance, initializing it lazily on first access.
func (*Client) ListenSOCKS5 ¶
ListenSOCKS5 starts a local SOCKS5 proxy server on localAddr (e.g. "127.0.0.1:1080"), routing all inbound connections through the remote SSH tunnel (equivalent to `ssh -D 1080`).
func (*Client) Run ¶
Run executes command on the remote host and returns its combined stdout and stderr.
func (*Client) ScriptFile ¶
ScriptFile reads localPath into memory and executes it as a script on the remote host.
func (*Client) Stream ¶
func (c *Client) Stream( ctx context.Context, command string, timeout time.Duration, ) (<-chan string, <-chan string, <-chan bool, <-chan error, error)
Stream executes command and streams stdout and stderr line-by-line over channels in real-time.
type Cmd ¶
type Cmd struct {
*ssh.Session
Path string
Args []string
Env []string
Cancel func() error
// contains filtered or unexported fields
}
Cmd represents an SSH command runner with context cancellation, signal control, and environment injection.
func (*Cmd) CombinedOutput ¶
CombinedOutput runs the command remotely and returns its combined stdout and stderr.
type CmdOption ¶
type CmdOption func(*Cmd)
CmdOption configures an SSH Cmd instance prior to execution.
func WithStderr ¶
WithStderr assigns a writer for remote command stderr.
func WithStdout ¶
WithStdout assigns a writer for remote command stdout.
type ContextDialer ¶
type ContextDialer interface {
DialContext(ctx context.Context, network, addr string) (net.Conn, error)
}
ContextDialer is a generic dialer capable of establishing network connections with a context.
type HostConfig ¶
type HostConfig struct {
Host string
HostName string
User string
Port uint
IdentityFiles []string
ProxyJump string
ProxyCommand string
StrictHostKeyChecking string
UserKnownHostsFile string
}
HostConfig holds options parsed from an OpenSSH config file for a specific host alias.
type Option ¶
type Option func(*Client, *ssh.ClientConfig) error
Option configures an SSH Client and its underlying ssh.ClientConfig.
func WithAgentSocket ¶
WithAgentSocket configures SSH agent authentication over a Unix socket path.
func WithAuth ¶
func WithAuth(method ssh.AuthMethod) Option
WithAuth appends a custom ssh.AuthMethod to authentication options.
func WithBannerCallback ¶
func WithBannerCallback(cb ssh.BannerCallback) Option
WithBannerCallback sets a banner message callback function.
func WithCert ¶
WithCert configures public key authentication using raw OpenSSH certificate and private key PEM bytes.
func WithCertFile ¶
WithCertFile configures public key authentication using an OpenSSH certificate and private key file.
func WithCertSigner ¶
WithCertSigner appends authentication using an existing certificate-backed ssh.Signer.
func WithCiphers ¶
WithCiphers overrides or appends accepted SSH ciphers.
func WithConfig ¶
func WithConfig(fn func(*ssh.ClientConfig) error) Option
WithConfig applies a custom modification callback to the underlying ssh.ClientConfig.
func WithDefaultAgent ¶
func WithDefaultAgent() Option
WithDefaultAgent configures SSH agent authentication using SSH_AUTH_SOCK.
func WithDialer ¶
func WithDialer(dialer ContextDialer) Option
WithDialer routes the underlying SSH connection through a custom ContextDialer transport.
func WithEnsureKnownHosts ¶
WithEnsureKnownHosts configures host key verification using path, creating the file if missing.
func WithFingerprint ¶
WithFingerprint verifies host key against an explicit SHA256 fingerprint string without requiring known_hosts.
func WithHighPerformanceDefaults ¶
func WithHighPerformanceDefaults() Option
WithHighPerformanceDefaults configures AEAD ciphers, fast KEX curves, and large channel window scaling.
func WithHostKeyAlgorithms ¶
WithHostKeyAlgorithms sets custom accepted host key algorithms.
func WithHostKeyCallback ¶
func WithHostKeyCallback(cb ssh.HostKeyCallback) Option
WithHostKeyCallback sets a custom host key callback function.
func WithInsecureIgnoreHostKey ¶
func WithInsecureIgnoreHostKey() Option
WithInsecureIgnoreHostKey disables host key verification.
func WithKeyExchanges ¶
WithKeyExchanges overrides or appends accepted Key Exchange algorithms.
func WithKeyFile ¶
WithKeyFile configures public key authentication from a private key file path.
func WithKeyboardInteractive ¶
func WithKeyboardInteractive(handler func(user, instruction, question string, echo bool) (string, error)) Option
WithKeyboardInteractive configures interactive prompt-response authentication.
func WithKnownHosts ¶
WithKnownHosts configures host key verification using path.
func WithLegacyCiphers ¶
func WithLegacyCiphers() Option
WithLegacyCiphers enables legacy ciphers and KEX algorithms.
func WithMaxPacketSize ¶
WithMaxPacketSize sets the maximum SSH packet size in bytes.
func WithPassword ¶
WithPassword configures password authentication.
func WithPtyTerminal ¶
WithPtyTerminal configures pseudo-terminal dimensions and terminal type.
func WithRequestPty ¶
WithRequestPty enables pseudo-terminal (PTY) allocation on sessions created by this client.
func WithSigner ¶
WithSigner appends public key authentication from an ssh.Signer.
func WithTimeout ¶
WithTimeout sets the SSH handshake connection timeout.
func WithWindowSize ¶
WithWindowSize sets the SSH channel initial window size in bytes.
type SSHConfig ¶
type SSHConfig struct {
Hosts map[string]*HostConfig
}
SSHConfig represents a parsed OpenSSH config file containing host entries.
func ParseSSHConfig ¶
ParseSSHConfig parses OpenSSH config directives from reader.
func ParseSSHConfigFile ¶
ParseSSHConfigFile loads and parses an OpenSSH config file from path. If path is empty, defaults to ~/.ssh/config.
func (*SSHConfig) GetHost ¶
func (cfg *SSHConfig) GetHost(alias string) *HostConfig
GetHost retrieves the HostConfig matching alias, falling back to wildcard '*' settings.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package agent provides SSH agent socket authentication utilities.
|
Package agent provides SSH agent socket authentication utilities. |
|
Package reverse provides a reverse SSH tunnel client for exposing local services.
|
Package reverse provides a reverse SSH tunnel client for exposing local services. |
|
Package sftp provides high-performance SFTP and SCP file transfer services over SSH sessions.
|
Package sftp provides high-performance SFTP and SCP file transfer services over SSH sessions. |