ssh

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: MIT Imports: 39 Imported by: 1 module, 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

Index

Constants

View Source
const (
	// Bound both original and quoted payloads below SSH transport packet and
	// common per-argument limits; remote servers may impose smaller limits.
	MaxCommandBytes       = 64 << 10
	MaxCommandInputBytes  = 16 << 20
	DefaultCommandOutput  = 5 << 20
	MaxCommandOutput      = 64 << 20
	DefaultCommandTimeout = 5 * time.Minute
)
View Source
const (
	DefaultKeepAliveInterval = 15 * time.Second
	DefaultKeepAliveTimeout  = 10 * time.Second
)

心跳默认参数:接收空闲 15s 后探测;等待回复期间连续 10s 无接收进展才超时。 网络拥塞下的有效接收进展会推迟探测或刷新等待时间,网络黑洞仍有确定的退出路径。

View Source
const (
	// MaxCmdPayloadBytes is the maximum command line length accepted by cmd.exe (8191 characters).
	MaxCmdPayloadBytes = 8191

	// MaxPowerShellPayloadBytes is the maximum command line length accepted by CreateProcess (32767 characters).
	MaxPowerShellPayloadBytes = 32767
)
View Source
const (
	DefaultInteractionTimeout = 2 * time.Minute
)
View Source
const DefaultPasswordPromptPattern = `` /* 126-byte string literal not displayed */

DefaultPasswordPromptPattern 是内置的多语言密码提示正则,覆盖主流语言环境。 匹配规则:密码关键词后面可以跟其他单词(如 "for user"),之后出现冒号即触发。

Variables

View Source
var (
	// ErrHostKeyMismatch 主机密钥不匹配或不受信任
	ErrHostKeyMismatch = errors.New("host key verification failed")
	// ErrPasswordRequired 需要密码但未提供
	ErrPasswordRequired = errors.New("password required but empty")
	// ErrKeyPathRequired 需要私钥路径但未提供
	ErrKeyPathRequired = errors.New("private key path required but empty")
	// ErrAgentNotAvailable SSH Agent 不可用
	ErrAgentNotAvailable = errors.New("ssh-agent socket not available")
	// ErrProxyCycle 代理跳转环路
	ErrProxyCycle = errors.New("proxy jump cycle detected")
)
View Source
var ErrConnectorClosed = errors.New("ssh connector is closed")

ErrConnectorClosed 表示 Connector 已执行 CloseAll,不能再建立或返回连接。

View Source
var ErrExecutionProbe = errors.New("SSH execution probe failed")

ErrExecutionProbe identifies an inconclusive or failed execution probe.

View Source
var ErrExecutionValidation = errors.New("execution validation error")

ErrExecutionValidation indicates an invalid execution configuration.

View Source
var ErrHandshakeClosed = errors.New("handshake coordinator is closed")

ErrHandshakeClosed 表示握手协调器已关闭或已被 fail-closed 中断。

View Source
var ErrInteractionRequired = errors.New("ssh interaction required")

ErrInteractionRequired 表示需要交互式输入但在非交互模式下被拒绝。

View Source
var ErrSnapshotMismatch = errors.New("connection snapshot mismatch")

ErrSnapshotMismatch 表示连接快照与当前配置版本或目标不匹配

Functions

func BindOutput

func BindOutput(ctx context.Context, target io.Writer) (writer io.Writer, closeFn func() error, cancelable bool, err error)

BindOutput prepares a non-PTY command output sink so that canceling ctx does not leave the SSH session waiting for a blocked write.

ContextWriter implementations, finite memory sinks, io.Discard, the null device, local regular files, and (on Linux) terminals and pipes are bound to ctx. Terminals and pipes use an owned non-blocking handle: the caller's file is never closed and its descriptor flags are not modified. Unlike PTY output, no per-write idle limit is applied, so a slow consumer such as a pager is not treated as a failure; only ctx cancellation or its deadline interrupts a stalled write.

Any other writer is returned unchanged with cancelable=false: arbitrary Write callbacks cannot be interrupted, and wrapping them in a goroutine would merely hide the leak. The caller owns that writer and must keep it non-blocking. closeFn must be called after all writes have finished and releases only resources created by BindOutput.

func ConnectionKey

func ConnectionKey(plan ConnectionPlan) (string, error)

ConnectionKey hashes the complete normalized plan, including source and trust versions. It is not a file-transfer destination lock or authorization.

func FormatWorkingDirCommand

func FormatWorkingDirCommand(cwd, command string, execution *ExecutionConfig) (string, error)

FormatWorkingDirCommand formats a command prepended with working directory change based on the execution configuration, or returns an error if cwd cannot be applied.

func NeedsExecutionProbe

func NeedsExecutionProbe(execution *ExecutionConfig) bool

NeedsExecutionProbe identifies an unspecified interpreter and unknown outer dialect. Explicit interpreter choices, including server, are never replaced.

func NormalizeWindowsSFTPWorkingDir

func NormalizeWindowsSFTPWorkingDir(cwd string) string

NormalizeWindowsSFTPWorkingDir converts OpenSSH SFTP drive paths /C:/... to C:/... for cmd.exe and Windows PowerShell. Other paths stay untouched. Callers must establish Windows semantics before using it.

func StartKeepAlive

func StartKeepAlive(ctx context.Context, client *ssh.Client, interval, timeout time.Duration, fallback func(err error)) <-chan struct{}

StartKeepAlive 开启一个协程,定期向 SSH Server 发送心跳 ctx: 用于控制协程退出的上下文 client: 目标 SSH 客户端 interval: 接收空闲探测间隔 (建议 15s - 60s) timeout: 等待心跳回复期间允许连续无接收进展的时间 (建议 5s - 15s) fallback: 可选的回调函数,用于在心跳失败后执行,心跳失败时会关闭连接 返回的通道在心跳 goroutine 完全退出后关闭,调用方可据此等待资源回收。 client.Close 必须能解除本地 I/O 阻塞;嵌套 ProxyJump 使用 Connector.EnableKeepAlive 或 Client.Wait,由连接所有者提供最外层传输的中断路径。 接收进展由 Connector 创建的连接提供;外部构造的 client 保留固定探测超时。

func StaticRespond

func StaticRespond(s string) func() (string, error)

StaticRespond 返回一个固定字符串的 Respond 回调。

Types

type AuthMaterial

type AuthMaterial struct {
	Password   []byte
	Passphrase []byte
}

AuthMaterial 包含单次 SSH 握手所需的敏感认证材料。

func (*AuthMaterial) Zero

func (a *AuthMaterial) Zero()

Zero 清零敏感字节切片并清空引用。

type AuthMethod

type AuthMethod interface {
	GetMethod() (ssh.AuthMethod, error)
}

AuthMethod 定义获取 SSH 认证方法的接口

type AuthenticatedConnectionConfirmer

type AuthenticatedConnectionConfirmer interface {
	ConfirmAuthenticatedConnection(context.Context, string, *Client) (*ExecutionConfig, error)
}

AuthenticatedConnectionConfirmer optionally inspects an authenticated client before enrollment and credential recording. It may run bounded read-only probes but must not retain/close the client or execute user commands. Implementations own confirmation and may return newly persisted execution defaults for this client; nil preserves its frozen defaults. ConnectionConfirmer is the fallback.

type AutoAuthOptions

type AutoAuthOptions struct {
	AgentSocket        string
	DefaultKeyPaths    []string
	ResolveKeyPath     func(string) string
	LifecycleCtx       context.Context
	NodeID             string
	User               string
	Host               string
	Port               int
	VersionToken       string
	Resolver           SecretResolver
	Prompter           SecretPrompter
	HandshakeTimeout   time.Duration
	InteractionTimeout time.Duration
	FailClosed         func(error)
	RecoveryPrompter   SecretPrompter
	KeyPath            string
	PasswordCallback   func(string)
	PassphraseCallback func(keyPath, passphrase string)
	Logger             logger.DebugLogger
}

AutoAuthOptions 封装 auto 认证的完整上下文选项。

type CPUTicks

type CPUTicks struct {
	User    uint64 `json:"user"`
	Nice    uint64 `json:"nice"`
	Sys     uint64 `json:"sys"`
	Idle    uint64 `json:"idle"`
	Iowait  uint64 `json:"iowait"`
	Irq     uint64 `json:"irq"`
	Softirq uint64 `json:"softirq"`
	Steal   uint64 `json:"steal"`
}

func (*CPUTicks) IdleTicks

func (t *CPUTicks) IdleTicks() uint64

func (*CPUTicks) Total

func (t *CPUTicks) Total() uint64

type Client

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

func NewTestClient

func NewTestClient(connCfg ConnectionConfig) *Client

NewTestClient creates a Client for unit testing with the provided connection config.

func NewTestClientWithRaw

func NewTestClientWithRaw(rawClient *ssh.Client, connCfg ConnectionConfig) *Client

NewTestClientWithRaw creates a Client for unit testing with an underlying raw SSH client.

func (*Client) AuthMaterial

func (c *Client) AuthMaterial() *AuthMaterial

AuthMaterial returns authentication material held by the client. Connected and pooled clients retain no AuthMaterial, always returning nil.

func (*Client) CachedExecutionProbe

func (c *Client) CachedExecutionProbe() (*ProbeResult, bool)

CachedExecutionProbe returns an already completed diagnostic snapshot without starting or waiting for network work. A failed or running probe returns false.

func (*Client) Close

func (c *Client) Close() error

func (*Client) Config

func (c *Client) Config() *ClientConfig

Config returns a snapshot of the node configuration. Mutating the returned value never changes the live client configuration. The snapshot contains no plaintext secrets (Password, Passphrase, SuPwd are always empty).

func (*Client) ConnectionConfig

func (c *Client) ConnectionConfig() ConnectionConfig

ConnectionConfig returns a copy of the live connection configuration.

func (*Client) ExecuteCommand

func (c *Client) ExecuteCommand(ctx context.Context, plan CommandPlan) CommandResult

ExecuteCommand sends a frozen command exactly once with finite stdin and internally bounded output. It does not accept external writers or request a PTY, perform privilege escalation, probe the server, or retry execution. All workers are joined; closing a stuck channel may interrupt the shared transport, including other operations using the same ProxyJump connection.

func (*Client) Execution

func (c *Client) Execution() *ExecutionConfig

Execution returns the configured execution configuration for this client, or nil.

func (*Client) Interrupt

func (c *Client) Interrupt() error

Interrupt closes the underlying transport forcefully and synchronously. Closing the physical connection unblocks I/O without relying on a peer reply or manufacturing deadline errors in the SSH transport. For ProxyJump this closes the outermost transport and all clients sharing it.

func (*Client) LocalForward

func (c *Client) LocalForward(ctx context.Context, localAddr, remoteAddr string, opts ...ForwardOption) (*Forward, error)

LocalForward starts local port forwarding. Listens on localAddr, forwards connections to remoteAddr via SSH.

func (*Client) ProbeControlledExecution

func (c *Client) ProbeControlledExecution(ctx context.Context, execution *ExecutionConfig) (*ExecutionConfig, error)

ProbeControlledExecution resolves a missing adapter for a restricted operation. Call only before script/ensure/cwd validation, never after a user command has started. Results share the Client's bounded probe cache; neither live command defaults nor disk configuration are changed. Consumers must still validate whether their operation supports the detected adapter.

func (*Client) ProbeExecutionConfig

func (c *Client) ProbeExecutionConfig(ctx context.Context) (*ProbeResult, error)

ProbeExecutionConfig performs a read-only, bounded two-stage probe. Successful results and non-context failures are shared for the authenticated connection's lifetime, including pooled wrappers. Concurrent callers share one attempt; each waiter can cancel independently. Non-context failures are cached, preventing repeated probes of restricted servers. A canceled or expired attempt can be retried by a later caller; its original waiters still receive its own result. This method neither changes Execution() nor writes configuration or retries user commands. A new connection is required to retry non-context failures.

func (*Client) RemoteForward

func (c *Client) RemoteForward(ctx context.Context, remoteAddr, localAddr string, opts ...ForwardOption) (*Forward, error)

RemoteForward starts remote port forwarding. Asks SSH server to listen on remoteAddr, forwards connections to localAddr. Startup and listener shutdown have independent, bounded request lifetimes. Canceling startup or timing out a request interrupts the shared SSH transport.

func (*Client) ResolveWorkingDirectoryExecution

func (c *Client) ResolveWorkingDirectoryExecution(ctx context.Context, execution *ExecutionConfig) (*ExecutionConfig, error)

ResolveWorkingDirectoryExecution selects an adapter for one cwd-aware command. A known server/cmd configuration has native CMD semantics, so CMD can apply the directory without changing command language. Keep this derived adapter session-local; unspecified configurations still use the bounded probe.

func (*Client) Run

func (c *Client) Run(ctx context.Context, cmd string, opts ...RunOption) (string, error)

func (*Client) RunCommandPlanWithIO

func (c *Client) RunCommandPlanWithIO(ctx context.Context, plan CommandPlan, stdin io.Reader, stdout, stderr io.Writer) (retErr error)

RunCommandPlanWithIO executes a frozen command plan with streaming stdin, stdout and stderr, without a PTY, privilege escalation, or replay.

stdin is borrowed and follows the RunCommandWithIO ownership contract (nil, an *os.File, or a finite in-memory reader); EOF closes only the sending direction. The plan must not carry finite input of its own: runtime stdin and plan input are never concatenated. stdout and stderr must be non-nil and cancelable as described by BindOutput; arbitrary writers are rejected before the command is sent. The plan's total timeout applies. A confirmed non-zero exit, signal or missing status is returned as an *ssh.ExitError or *ssh.ExitMissingError wrapped with context. Output is not retained.

func (*Client) RunCommandWithIO

func (c *Client) RunCommandWithIO(ctx context.Context, command string, sudo bool, stdin io.Reader, stdout, stderr io.Writer) (retErr error)

RunCommandWithIO executes a command (or interactive bash when command is empty) using caller-provided I/O streams. If sudo is true, it escalates privileges according to the target node's SudoMode. stdin is borrowed from the caller and will never be closed by this method. To guarantee cancellation without leaking a goroutine, stdin must be nil, an *os.File, or a finite in-memory *bytes.Buffer, *bytes.Reader, or *strings.Reader. Use RunCommandWithInput for arbitrary finite input bytes.

func (*Client) RunCommandWithInput

func (c *Client) RunCommandWithInput(ctx context.Context, command string, input []byte, stdout, stderr io.Writer) error

RunCommandWithInput executes a command (or interactive bash when command is empty) using finite byte input.

func (*Client) RunInteractive

func (c *Client) RunInteractive(ctx context.Context, cmd string) error

RunInteractive runs one command in a PTY using an SSH exec request. A non-interactive login bash loads the login environment without starting a prompt or writing the command through the terminal's echoed input stream.

func (*Client) RunInteractiveCmd

func (c *Client) RunInteractiveCmd(ctx context.Context, cmd string) error

RunInteractiveCmd 在 PTY 环境下直接执行命令(通过 SSH exec 通道,不启动交互式 shell), 不会产生登录信息或命令回显,适合在已有 shell 环境内调用 vim/top 等程序。

func (*Client) RunInteractiveCmdWithIO

func (c *Client) RunInteractiveCmdWithIO(ctx context.Context, cmd string, streams InteractiveIO) error

RunInteractiveCmdWithIO runs one PTY-backed command using caller-provided streams.

func (*Client) RunInteractivePlan

func (c *Client) RunInteractivePlan(ctx context.Context, plan CommandPlan) error

RunInteractivePlan executes a validated command plan in a PTY with the environment's terminal streams. stdin belongs to the terminal, not the plan.

func (*Client) RunInteractivePlanWithIO

func (c *Client) RunInteractivePlanWithIO(ctx context.Context, plan CommandPlan, streams InteractiveIO) (retErr error)

RunInteractivePlanWithIO requires local terminal input and finite or context-aware output. Native Linux files must be terminals/pipes; other native file bridges and regular-file redirection require subsequent acceptance.

func (*Client) RunInteractiveWithOptions

func (c *Client) RunInteractiveWithOptions(ctx context.Context, command string, opts ...RunOption) error

RunInteractiveWithOptions preserves the legacy login default while honoring an explicit WithLoginShell override. Terminal I/O is supplied by Environment.

func (*Client) RunInteractiveWithSudo

func (c *Client) RunInteractiveWithSudo(ctx context.Context, command string) error

RunInteractiveWithSudo 在 PTY 环境下以提权方式执行单条交互式命令

func (*Client) RunInteractiveWithSudoIO

func (c *Client) RunInteractiveWithSudoIO(ctx context.Context, command string, streams InteractiveIO) error

RunInteractiveWithSudoIO uses an authenticated terminal handoff before consuming caller input. The injected streams avoid process-global I/O changes.

func (*Client) RunScript

func (c *Client) RunScript(ctx context.Context, scriptContent string, opts ...RunOption) (output string, retErr error)

RunScript 执行 Shell 脚本内容

func (*Client) RunScriptWithExecution

func (c *Client) RunScriptWithExecution(ctx context.Context, content string, execution *ExecutionConfig, extraOpts ...RunOption) (string, error)

RunScriptWithExecution applies the resolved execution configuration to RunScript.

func (*Client) RunScriptWithSudo

func (c *Client) RunScriptWithSudo(ctx context.Context, scriptContent string, opts ...RunOption) (string, error)

RunScriptWithSudo 提权执行脚本

func (*Client) RunScriptWithSudoExecution

func (c *Client) RunScriptWithSudoExecution(ctx context.Context, content string, execution *ExecutionConfig, extraOpts ...RunOption) (string, error)

RunScriptWithSudoExecution applies the same target/login capability checks to a script whose interpreter has already been resolved by the caller.

func (*Client) RunShellWithIO

func (c *Client) RunShellWithIO(ctx context.Context, stdin io.Reader, stdout, stderr io.Writer) (retErr error)

RunShellWithIO sends an SSH shell request without a PTY using caller-provided I/O streams. Unlike RunShellWithoutPTY, which enforces strict output cancelability, RunShellWithIO allows uncancelable outputs on platforms where native cancelable output is unavailable.

func (*Client) RunShellWithoutPTY

func (c *Client) RunShellWithoutPTY(ctx context.Context, stdin io.Reader, stdout, stderr io.Writer) (retErr error)

RunShellWithoutPTY sends an SSH shell request without a PTY and forwards streaming stdin. It is for non-terminal input to a server shell: no interpreter is inserted, no empty exec request is sent, and unlike a full login terminal session the remote exit status is retained. Input, output and cancellation follow RunCommandPlanWithIO. Duration is controlled by ctx.

func (*Client) RunStream

func (c *Client) RunStream(ctx context.Context, cmd string) (io.ReadCloser, error)

RunStream 执行命令并返回流式输出

func (*Client) RunWithSudo

func (c *Client) RunWithSudo(ctx context.Context, command string, opts ...RunOption) (string, error)

func (*Client) RunWithSudoExecution

func (c *Client) RunWithSudoExecution(ctx context.Context, command string, execution *ExecutionConfig) (string, error)

RunWithSudoExecution honors a frozen execution configuration or rejects an unvalidated escalation adapter. Nil configuration preserves legacy behavior.

func (*Client) RunWithoutLogin

func (c *Client) RunWithoutLogin(ctx context.Context, cmd string) (string, error)

RunWithoutLogin 执行命令并在非登录 Shell 中运行,避免加载 profile 脚本产生干扰输出

func (*Client) SSHClient

func (c *Client) SSHClient() *ssh.Client

func (*Client) Shell

func (c *Client) Shell(ctx context.Context) error

func (*Client) ShellWithIO

func (c *Client) ShellWithIO(ctx context.Context, streams InteractiveIO) error

ShellWithIO starts an interactive remote shell using caller-provided streams.

func (*Client) ShellWithSudo

func (c *Client) ShellWithSudo(ctx context.Context) error

ShellWithSudo opens an interactive privileged shell using the default streams.

func (*Client) ShellWithSudoIO

func (c *Client) ShellWithSudoIO(ctx context.Context, streams InteractiveIO) error

ShellWithSudoIO authenticates before switching the local terminal to raw mode.

func (*Client) Socks5Forward

func (c *Client) Socks5Forward(ctx context.Context, listenAddr string, opts ...ForwardOption) (*Forward, error)

Socks5Forward starts a SOCKS5 proxy server on listenAddr, forwarding traffic via SSH.

func (*Client) Wait

func (c *Client) Wait(ctx context.Context) error

Wait monitors the SSH transport, probing idle connections to detect network loss. It closes the client before returning and joins its transport waiter. Caller cancellation returns only cleanup errors; transport loss is an error. Receive progress postpones idle probes and extends pending probe timeouts. Cancellation or a failed probe aborts the entire shared ProxyJump transport.

type ClientConfig

type ClientConfig struct {
	KeyRef       string
	TrustVersion string
	NodeID       string // 逻辑标识
	Address      string
	Port         int
	User         string
	AuthType     string // "password", "key", "agent", "auto"
	Password     string
	KeyPath      string
	Passphrase   string
	// AuthUpdateToken conditionally authorizes persistence of discovered
	// authentication values. An empty token makes discovery session-local.
	AuthUpdateToken string
	SudoMode        SudoMode // "root", "sudo", "sudoer", "su", "none", "auto"
	SuPwd           string
	// SudoUpdateToken conditionally authorizes persistence of discovered sudo
	// values. An empty token makes discovery session-local.
	SudoUpdateToken      string
	ProxyJump            string // 跳板机的 NodeID
	OriginalProxyJump    string // 来自 Provider 的原始 ProxyJump 配置(用于目标一致性变更检查)
	HasOriginalProxyJump bool   // 是否显式保留了配置态 ProxyJump 快照(区分显式空字符串与未设置)
	// PasswordPromptPattern 自定义密码提示正则(节点级,可选)。
	// 为空时回落到 Connector 的全局配置,再为空则使用内置的多语言默认模式。
	PasswordPromptPattern string
	Execution             *ExecutionConfig
}

ClientConfig 定义建立 SSH 连接所需的各种参数,代替原有的 models.Node/Host/Identity。

func (*ClientConfig) ToConnectionConfig

func (c *ClientConfig) ToConnectionConfig() ConnectionConfig

ToConnectionConfig 将 ClientConfig 转换为仅含网络与连接参数的 ConnectionConfig,剥离所有明文密码。

type CommandExitError

type CommandExitError struct {
	ExitCode *uint32
	Signal   string
}

CommandExitError reports a confirmed unsuccessful remote termination.

func (*CommandExitError) Error

func (e *CommandExitError) Error() string

type CommandOptions

type CommandOptions struct {
	Interpreter   Interpreter
	LaunchDialect LaunchDialect
	Login         LoginMode
	Stdin         []byte
	Timeout       time.Duration
	OutputLimit   int
}

CommandOptions is copied into an immutable CommandPlan. Stdin is finite user data, never a second command or an interpreter-selection probe. Timeout zero and OutputLimit zero select bounded defaults; negative values are invalid.

type CommandPlan

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

CommandPlan is immutable and safe to share across execution attempts. The zero value is invalid. Accessors return values, never mutable internal state. Digest binds command semantics and input but is not an authorization permit.

func PlanCommand

func PlanCommand(command string, options CommandOptions) (CommandPlan, error)

PlanCommand validates and freezes one ordinary command without network I/O. It never performs OS detection or fallback. Unix adapters require a known POSIX or fish outer shell; server preserves command bytes and accepts only inherited login mode.

func (CommandPlan) Command

func (p CommandPlan) Command() string

func (CommandPlan) Digest

func (p CommandPlan) Digest() string

func (CommandPlan) Interpreter

func (p CommandPlan) Interpreter() Interpreter

func (CommandPlan) LaunchDialect

func (p CommandPlan) LaunchDialect() LaunchDialect

func (CommandPlan) LoginMode

func (p CommandPlan) LoginMode() LoginMode

func (CommandPlan) Payload

func (p CommandPlan) Payload() string

type CommandResult

type CommandResult struct {
	PlanDigest   string
	Phase        string
	Outcome      ExecutionOutcome
	ExitCode     *uint32
	Signal       string
	Output       string
	Truncated    bool
	ExecutionErr error
	IOErr        error
	CleanupErr   error
}

CommandResult retains remote termination independently of local I/O/cleanup failures. ExitCode is nil if no exit-status was received, including signals.

func (CommandResult) Err

func (r CommandResult) Err() error

type ConfigStore

type ConfigStore interface {
	ConnectionProvider
	CredentialRecorder
}

ConfigStore 聚合 ConnectionProvider 和 CredentialRecorder 接口。 Deprecated: 请优先使用拆分后的小接口 ConnectionProvider, SecretResolver, CredentialRecorder。

type ConnectionConfig

type ConnectionConfig struct {
	KeyRef                string
	TrustVersion          string
	NodeID                string
	Address               string
	Port                  int
	User                  string
	AuthType              string
	KeyPath               string
	AuthUpdateToken       string
	SudoMode              SudoMode
	SudoUpdateToken       string
	ProxyJump             string
	OriginalProxyJump     string
	HasOriginalProxyJump  bool
	PasswordPromptPattern string
	Execution             *ExecutionConfig
}

ConnectionConfig 包含建立连接所需的目标与网络参数,不包含登录或提权明文机密。

type ConnectionConfirmer

type ConnectionConfirmer interface {
	ConfirmConnection(context.Context, string) error
}

ConnectionConfirmer is an optional provider capability invoked immediately after SSH authentication, before recording credentials or dispatching user work.

type ConnectionError

type ConnectionError struct {
	NodeID   string
	Address  string
	Port     int
	AuthType string
	Err      error
}

ConnectionError 携带节点连接相关的结构化上下文

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

func (*ConnectionError) Unwrap

func (e *ConnectionError) Unwrap() error

type ConnectionPlan

type ConnectionPlan struct {
	Scope string
	Hops  []ConnectionConfig
}

ConnectionPlan is an immutable connection snapshot. Hops are ordered from the first directly reachable jump to the final target, without plaintext secrets. Scope separates consumers that share node names or credentials.

func CapturePlan

func CapturePlan(ctx context.Context, provider ConnectionProvider, nodeID, scope string) (_ ConnectionPlan, retErr error)

CapturePlan resolves a complete snapshot from a host-supplied immutable in-memory provider. It never dials or retains that provider after returning.

type ConnectionProvider

type ConnectionProvider interface {
	// GetConfig 获取指定 nodeID 的连接配置
	GetConfig(nodeID string) (*ClientConfig, error)
}

ConnectionProvider 提供指定节点的底层连接配置。

type Connector

type Connector struct {

	// 自动接受新的主机密钥
	AcceptNewHostKey atomic.Bool
	// PasswordPromptPattern 全局级自定义密码提示正则(可选)。
	// 当节点的 ClientConfig.PasswordPromptPattern 为空时,使用此值;
	// 两者均为空则使用内置的 DefaultPasswordPromptPattern。
	PasswordPromptPattern string
	// contains filtered or unexported fields
}

Connector 负责创建 SSH 连接

func NewConnector

func NewConnector(provider ConnectionProvider, opts ...Option) *Connector

NewConnector 创建一个新的 Connector,支持 Functional Options。 支持接收 ConnectionProvider 或兼容的 ConfigStore。

func (*Connector) CloseAll

func (c *Connector) CloseAll() error

CloseAll 关闭所有缓存的连接并等待在途建连与心跳 goroutine 退出。 调用后 Connector 进入永久关闭状态,后续 Connect 返回 ErrConnectorClosed。

func (*Connector) Connect

func (c *Connector) Connect(ctx context.Context, nodeName string) (*Client, error)

Connect 根据节点名称建立 SSH 连接。 ProxyJump 链会先完整解析并检测环,再从最底层跳板机开始逐层建立连接。

func (*Connector) ConnectPlan

func (c *Connector) ConnectPlan(ctx context.Context, plan ConnectionPlan) (*PlanConnection, error)

ConnectPlan never reads the connector's mutable ConnectionProvider. The source references and complete jump chain are copied into a generation-owned provider; legacy credential recording is disabled for these snapshots.

func (*Connector) EnableKeepAlive

func (c *Connector) EnableKeepAlive(ctx context.Context, interval, timeout time.Duration)

EnableKeepAlive 启用连接池周期心跳(opt-in,幂等)。 启用后所有新入池的连接(含 ProxyJump 跳板机连接)会挂载周期性 keepalive 探测: 接收数据会推迟空闲探测;等待回复期间持续接收数据会刷新超时。 探测失败或持续无接收进展直到超时才关闭连接并从池中驱逐,下次 Connect 自动重建。 interval/timeout 传非正值时回退到 DefaultKeepAliveInterval/DefaultKeepAliveTimeout。 Connect 的缓存复检以 timeout 为总时限,不随接收进展延长。 生命周期同时绑定 ctx 与 CloseAll:任一方取消都会终止全部心跳 goroutine 并清理配置; ctx 取消完成清理后允许再次启用,CloseAll 之后则不会恢复。 仅对启用后入池的连接生效,存量连接不补挂。 适用于 MCP server 等长驻进程;CLI 短生命周期命令无需启用(Connect 的缓存探测已兜底)。

func (*Connector) RetirePlan

func (c *Connector) RetirePlan(plan ConnectionPlan) error

RetirePlan stops new reuse of this cached generation and drains its existing leases. This is cache invalidation, not authorization/revocation: callers must check current operation bindings before requesting any plan again.

type ContextWriter

type ContextWriter interface {
	WriteContext(context.Context, []byte) (int, error)
}

ContextWriter is an explicit output capability. Implementations must return when ctx is canceled, perform no writes after returning, and not retain data. Ordinary io.Writer callbacks cannot provide that guarantee automatically.

type CredentialFailureReporter

type CredentialFailureReporter interface {
	CredentialRecoveryAllowed() bool
	ReportCredentialFailure(context.Context, string) error
}

CredentialFailureReporter opts an interactive composition root into temporary credential recovery. Reports contain operation names only, never backend errors, which may contain secrets. Returning an error aborts recovery.

type CredentialRecorder

type CredentialRecorder interface {
	// UpdateAuth 在探测到可用密码或私钥 passphrase 时,写回持久化存储并返回本次提交后的新认证令牌
	UpdateAuth(ctx context.Context, nodeID, authUpdateToken, password, keyPath, passphrase string) (string, error)

	// UpdateSudo 在探测到可用提权模式或接收到 su 密码时,写回持久化存储并返回本次提交后的新提权令牌
	UpdateSudo(ctx context.Context, nodeID, sudoUpdateToken string, mode SudoMode, suPwd string) (string, error)
}

CredentialRecorder 负责将探测或交互获得的新凭据写回持久化存储。

type Dialer

type Dialer interface {
	Dial(network, addr string) (net.Conn, error)
	DialContext(ctx context.Context, network, addr string) (net.Conn, error)
}

Dialer 定义网络连接行为的接口 用于统一 "直连" 和 "通过 SSH 跳板机连接" 的行为

type DiskMetric

type DiskMetric struct {
	MountPoint string
	Total      uint64 // MB
	Used       uint64 // MB
	Usage      float64
}

DiskMetric 存储单个分区的指标

type Environment

type Environment struct {
	InitializationError error
	KnownHostsFile      string
	AgentSocket         string
	DefaultKeyPaths     []string
	ResolveKeyPath      func(string) string
	InteractiveIO       InteractiveIO
	InputBridge         InputBridge
}

Environment supplies explicitly selected local resources. The core never discovers a home directory, SSH_AUTH_SOCK, or process standard streams. Slices are copied by WithEnvironment; callbacks must be concurrency-safe.

type ExecutionConfig

type ExecutionConfig struct {
	Interpreter   Interpreter   `yaml:"interpreter,omitempty" json:"interpreter,omitempty"`
	LaunchDialect LaunchDialect `yaml:"launch_dialect,omitempty" json:"launchDialect,omitempty"`
	Login         *bool         `yaml:"login,omitempty" json:"login,omitempty"`
}

ExecutionConfig specifies the execution environment for commands. It can be configured at global, node, playbook settings, or step levels.

func EffectiveExecution

func EffectiveExecution(layers ...*ExecutionConfig) (*ExecutionConfig, error)

EffectiveExecution resolves a hierarchy of execution configs from highest priority to lowest priority (e.g. step, settings, node, global).

func ResolveExecution

func ResolveExecution(child, parent *ExecutionConfig) (*ExecutionConfig, error)

ResolveExecution merges a child (higher priority) execution config with a parent (lower priority) execution config according to the inheritance rules:

  • launch_dialect inherits from parent unless explicitly overridden by child.
  • If child overrides interpreter to a different non-empty interpreter, parent's login option is NOT inherited (child's login applies, or nil).
  • If child does not override interpreter, parent's interpreter is inherited, and login inherits from parent unless child explicitly sets it.
  • Explicit incompatible combinations fail validation.

func ResolveScriptExecution

func ResolveScriptExecution(step, settings, node, global *ExecutionConfig, scriptBytes []byte) (*ExecutionConfig, error)

ResolveScriptExecution resolves the execution configuration for a script following the precedence order:

  1. Explicit Playbook step execution (step)
  2. Playbook settings execution (settings)
  3. Supported shebang declaration in script bytes
  4. Node execution (non-server only)
  5. Global execution (non-server only)

Explicitly selecting the server interpreter in step or settings returns an error. If the script declares an unsupported shebang without an explicit step or settings override, an error is returned. In Phase P3, scripts use the unified model by default and fail before execution if no reliable interpreter is available. If execution config is present or defaulted but no valid non-server script interpreter can be determined, an error is returned.

func (*ExecutionConfig) Clone

func (e *ExecutionConfig) Clone() *ExecutionConfig

Clone returns a deep copy of ExecutionConfig.

func (*ExecutionConfig) CommandOptions

func (e *ExecutionConfig) CommandOptions() CommandOptions

CommandOptions applies caller defaults, then converts execution config. In Phase P3, absence or unspecified interpreter defaults to InterpreterServer with LaunchUnknown and LoginInherit. An explicit interpreter uses its adapter defaults; server never inherits a POSIX launch assumption.

func (*ExecutionConfig) EffectiveInterpreter

func (e *ExecutionConfig) EffectiveInterpreter() Interpreter

EffectiveInterpreter returns the configured interpreter, or the default InterpreterServer if unspecified.

func (*ExecutionConfig) LoginMode

func (e *ExecutionConfig) LoginMode() LoginMode

LoginMode returns the effective LoginMode represented by the configuration.

func (ExecutionConfig) MarshalJSON

func (e ExecutionConfig) MarshalJSON() ([]byte, error)

MarshalJSON serializes ExecutionConfig using camelCase launchDialect.

func (*ExecutionConfig) SudoRunOptions

func (e *ExecutionConfig) SudoRunOptions(command string) ([]RunOption, error)

SudoRunOptions rejects unsupported escalation semantics before dispatch and maps the validated Bash, sh, zsh or fish mode to the sudo adapter explicitly. A nil config preserves the legacy POSIX Bash+login environment.

func (*ExecutionConfig) UnmarshalJSON

func (e *ExecutionConfig) UnmarshalJSON(data []byte) error

UnmarshalJSON strictly unmarshals and validates an ExecutionConfig from JSON, supporting both launchDialect and launch_dialect, and login as bool or string.

func (*ExecutionConfig) UnmarshalYAML

func (e *ExecutionConfig) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML strictly unmarshals and validates an ExecutionConfig from YAML, rejecting unknown fields.

func (*ExecutionConfig) Validate

func (e *ExecutionConfig) Validate() error

Validate validates that the execution configuration contains supported values and mutually compatible settings.

type ExecutionOutcome

type ExecutionOutcome string

ExecutionOutcome describes what is known about remote execution, not whether it succeeded. Unknown results must never be automatically replayed.

const (
	ExecutionNotStarted ExecutionOutcome = "not_started"
	ExecutionCompleted  ExecutionOutcome = "completed"
	ExecutionUnknown    ExecutionOutcome = "unknown"
)

type Expect

type Expect struct {
	Target io.Writer // 匹配过程中和完成后的透传目标(用于交互式 Shell 实时显示)
	// contains filtered or unexported fields
}

Expect 是一个被动的 io.Writer,拦截并分析 SSH 输出流,匹配多阶段交互。 通过实现 io.Writer,它消除了主动 Read 导致的 goroutine 泄露和数据竞争问题。

func NewExpect

func NewExpect(writer io.Writer, rules ...ExpectRule) *Expect

NewExpect 创建一个 Expect 实例。 writer 是自动响应的目标(例如 SSH 会话的 stdin)。 该构造器保留原有的可变参数 API;需要注入可选依赖时使用 NewExpectWithOptions。

func NewExpectWithOptions

func NewExpectWithOptions(writer io.Writer, rules []ExpectRule, opts ...ExpectOption) *Expect

NewExpectWithOptions 创建一个支持显式依赖注入的 Expect 实例。

func (*Expect) CleanOutput

func (e *Expect) CleanOutput(promptPattern *regexp.Regexp) string

CleanOutput 返回清理后的输出:剔除匹配 promptPattern 的密码输入行。

func (*Expect) Output

func (e *Expect) Output() string

Output 返回内部缓冲区累积的所有输出。

func (*Expect) SetAccumulate

func (e *Expect) SetAccumulate(acc bool)

SetAccumulate 设置是否在匹配结束后继续累积输出。 用于短生命周期的命令(如 runWithSu),以便执行完毕后获取完整输出。

func (*Expect) SetTarget

func (e *Expect) SetTarget(target io.Writer)

SetTarget 设置透传目标,所有 Write 进来的数据都会原样写入 target。

func (*Expect) Stop

func (e *Expect) Stop()

Stop 停止匹配逻辑,释放资源,不再缓冲多余数据(除非 accumulateAll=true)。

func (*Expect) Wait

func (e *Expect) Wait(ctx context.Context, timeout time.Duration) error

Wait 等待所有规则匹配完成、超时或 ctx 取消。 超时发生时,它会自动调用 Stop,后续不再进行任何正则匹配。

func (*Expect) Write

func (e *Expect) Write(p []byte) (n int, err error)

Write 实现了 io.Writer 接口,由 SSH 客户端底层主动调用,消除了竞态。

type ExpectOption

type ExpectOption func(*Expect)

ExpectOption 用于配置 Expect

func WithExpectLogger

func WithExpectLogger(l logger.DebugLogger) ExpectOption

WithExpectLogger 为 Expect 注入 DebugLogger(必须支持并发调用)

type ExpectRule

type ExpectRule struct {
	// Pattern 是用于匹配 PTY 输出的正则表达式。
	Pattern *regexp.Regexp

	// Respond 在 Pattern 命中后被调用,返回需要写入 stdin 的内容(不含换行符)。
	Respond func() (string, error)
}

ExpectRule 定义单条匹配规则:等待输出匹配 Pattern,然后调用 Respond 生成响应。

type Forward

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

Forward represents one running SSH port forward. Callers must either wait for it or cancel the context passed to its constructor.

func (*Forward) Addr

func (f *Forward) Addr() net.Addr

Addr returns the listener address, including a server-allocated port. For remote forwarding, the SSH server's GatewayPorts policy controls exposure; the returned host is not proof of the server's effective bind interfaces.

func (*Forward) Done

func (f *Forward) Done() <-chan struct{}

Done closes after the listener and all accepted connections have stopped.

func (*Forward) Wait

func (f *Forward) Wait() error

Wait blocks until the forwarding listener and all connection handlers exit. It is safe to call Wait more than once; every call returns the same result.

type ForwardOption

type ForwardOption func(*forwardOptions)

ForwardOption configures how a forwarding listener reports connection-level failures. These failures never stop the listener.

func WithForwardConnectionLimit

func WithForwardConnectionLimit(limit int) ForwardOption

WithForwardConnectionLimit bounds concurrent accepted connections. Excess connections are closed immediately. Nonpositive values leave the default unlimited behavior unchanged.

func WithForwardErrorHandler

func WithForwardErrorHandler(handler func(error)) ForwardOption

WithForwardErrorHandler receives errors isolated to one accepted connection. The callback must be safe for concurrent calls and return promptly.

type HandshakeError

type HandshakeError struct {
	NodeID string
	Err    error
}

HandshakeError 封装 SSH 协议握手失败的错误

func (*HandshakeError) Error

func (e *HandshakeError) Error() string

func (*HandshakeError) Unwrap

func (e *HandshakeError) Unwrap() error

type HostKeyAlgorithmSource

type HostKeyAlgorithmSource interface {
	HostKeyAlgorithms(context.Context, HostKeyRequest) ([]string, error)
}

HostKeyAlgorithmSource is an optional HostKeyVerifier capability. It selects host key algorithms before the handshake using the same target/trust version as Verify. Hostname and Remote are not available at this stage. Implementations must honor ctx; errors, empty lists and unsupported algorithms fail closed. Selection does not replace Verify or authorize a different key of that type.

type HostKeyConfirmation

type HostKeyConfirmation struct {
	Hostname      string
	RemoteAddress string
	Algorithm     string
	Fingerprint   string
}

HostKeyConfirmation 描述主机密钥指纹确认请求

type HostKeyConfirmer

type HostKeyConfirmer interface {
	ConfirmHostKey(ctx context.Context, request HostKeyConfirmation) (bool, error)
}

HostKeyConfirmer 负责提示用户确认未知的主机密钥

type HostKeyRequest

type HostKeyRequest struct {
	NodeID       string
	Host         string
	Port         int
	User         string
	VersionToken string
	Hostname     string
	Remote       net.Addr
}

HostKeyRequest binds trust verification to the connection being established.

type HostKeyVerifier

type HostKeyVerifier interface {
	Verify(context.Context, HostKeyRequest, cryptoSSH.PublicKey) error
}

HostKeyVerifier implementations must honor the handshake context and must not trust an unknown host implicitly.

type InputBridge

type InputBridge interface {
	Start(context.Context, InteractiveIO, io.Writer) (InputCopy, error)
}

InputBridge owns only duplicated input and cancellation handles. The caller owns the supplied terminal streams and the remote writer.

type InputCopy

type InputCopy interface {
	Close() error
	Wait(context.Context) error
}

InputCopy.Close interrupts reading; Wait joins the copy within its context. Closing a copy must not close any borrowed process standard stream.

func NewInputCopy

func NewInputCopy(ctx context.Context, cancel func() error, done <-chan error) (InputCopy, error)

NewInputCopy adapts a cancellable input pump. The pump must send exactly one completion result and exit when interrupted; cancellation must be bounded. The returned copy owns cancellation and joins the completion collector.

type InteractionHandler

type InteractionHandler interface {
	SecretPrompter
	HostKeyConfirmer
}

InteractionHandler 组合了机密提示与主机密钥确认接口

type InteractiveIO

type InteractiveIO struct {
	Stdin  *os.File
	Stdout io.Writer
	Stderr io.Writer
}

InteractiveIO supplies the terminal streams used by an interactive SSH operation. The caller owns these streams and their lifecycle.

type Interpreter

type Interpreter string

Interpreter selects how a command is executed, independently of the server's launch dialect. Only validated command adapters are exposed here.

const (
	InterpreterServer     Interpreter = "server"
	InterpreterBash       Interpreter = "bash"
	InterpreterSh         Interpreter = "sh"
	InterpreterFish       Interpreter = "fish"
	InterpreterZsh        Interpreter = "zsh"
	InterpreterPowerShell Interpreter = "powershell"
	InterpreterPwsh       Interpreter = "pwsh"
	InterpreterCmd        Interpreter = "cmd"
)

type KeyAuth

type KeyAuth struct {
	Path       string
	Passphrase string
}

KeyAuth 实现私钥认证

func (*KeyAuth) GetMethod

func (k *KeyAuth) GetMethod() (ssh.AuthMethod, error)

type KeyLease

type KeyLease interface {
	Signer() cryptoSSH.Signer
	Close() error
}

KeyLease is owned by the handshake and released on every success/error path. Implementations honor the OpenKey context and keep Close bounded.

type KeyRequest

type KeyRequest struct {
	NodeID       string
	Host         string
	Port         int
	User         string
	Reference    string
	Path         string
	VersionToken string
}

KeyRequest binds a signer to a target and version. Reference is opaque to SSH and never interpreted as a local path; Path is an explicit file hint.

type KeySource

type KeySource interface {
	OpenKey(context.Context, KeyRequest) (KeyLease, error)
}

type LaunchDialect

type LaunchDialect string

LaunchDialect describes the server shell parsing the SSH exec payload.

const (
	LaunchUnknown    LaunchDialect = "unknown"
	LaunchPOSIX      LaunchDialect = "posix"
	LaunchFish       LaunchDialect = "fish"
	LaunchPowerShell LaunchDialect = "powershell"
	LaunchCmd        LaunchDialect = "cmd"
)

type LockedWriter

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

LockedWriter 是一个并发安全的 io.Writer 包装器。 用于多个 goroutine 向同一目标(如 os.Stdout)写入时,保证写操作的原子性。

func NewLockedWriter

func NewLockedWriter(mu *sync.Mutex, w io.Writer) *LockedWriter

NewLockedWriter 创建一个并发安全的 Writer 包装器。

func (*LockedWriter) Write

func (lw *LockedWriter) Write(p []byte) (n int, err error)

type LoginMode

type LoginMode string

LoginMode preserves the distinction between omission and an explicit false.

const (
	LoginInherit  LoginMode = "inherit"
	LoginEnabled  LoginMode = "enabled"
	LoginDisabled LoginMode = "disabled"
)

type MetricsCollector

type MetricsCollector struct {
	SortBy  string // "cpu", "mem"
	SortAsc bool
	// contains filtered or unexported fields
}

func NewMetricsCollector

func NewMetricsCollector(c *Client) *MetricsCollector

func (*MetricsCollector) Close

func (mc *MetricsCollector) Close() error

func (*MetricsCollector) NextFrame

func (mc *MetricsCollector) NextFrame(ctx context.Context) (*SystemMetrics, error)

func (*MetricsCollector) SortConfig

func (mc *MetricsCollector) SortConfig() (string, bool)

SortConfig returns a stable snapshot of display ordering preferences.

func (*MetricsCollector) Start

func (mc *MetricsCollector) Start(ctx context.Context) error

func (*MetricsCollector) ToggleSortBy

func (mc *MetricsCollector) ToggleSortBy()

ToggleSortBy switches the display ordering without racing an in-flight frame decode.

func (*MetricsCollector) ToggleSortOrder

func (mc *MetricsCollector) ToggleSortOrder()

ToggleSortOrder reverses the display ordering without racing an in-flight frame decode.

type Option

type Option func(*Connector)

Option 用于配置 Connector

func WithConnectionProvider

func WithConnectionProvider(provider ConnectionProvider) Option

WithConnectionProvider 配置连接配置提供者

func WithCredentialRecorder

func WithCredentialRecorder(recorder CredentialRecorder) Option

WithCredentialRecorder 配置凭据写回记录器(传 nil 时回退到默认 nop recorder)

func WithDialer

func WithDialer(dialer Dialer) Option

WithDialer 配置底层直连所使用的自定义 Dialer

func WithEnvironment

func WithEnvironment(environment Environment) Option

func WithHandshakeTimeout

func WithHandshakeTimeout(timeout time.Duration) Option

WithHandshakeTimeout 配置底层 SSH 握手网络超时时间

func WithHostKeyConfirmer

func WithHostKeyConfirmer(confirmer HostKeyConfirmer) Option

WithHostKeyConfirmer 单独配置主机密钥确认器

func WithHostKeyVerifier

func WithHostKeyVerifier(verifier HostKeyVerifier) Option

func WithInteractionHandler

func WithInteractionHandler(handler InteractionHandler) Option

WithInteractionHandler 配置交互处理器(同时设置 SecretPrompter 和 HostKeyConfirmer)

func WithInteractionTimeout

func WithInteractionTimeout(timeout time.Duration) Option

WithInteractionTimeout 配置单次交互提示超时时间

func WithKeySource

func WithKeySource(source KeySource) Option

func WithLogger

func WithLogger(l logger.DebugLogger) Option

WithLogger 配置 Connector 使用的 DebugLogger(必须支持并发调用)

func WithPasswordPromptPattern

func WithPasswordPromptPattern(pattern string) Option

WithPasswordPromptPattern 配置密码匹配正则

func WithSecretPrompter

func WithSecretPrompter(prompter SecretPrompter) Option

WithSecretPrompter 单独配置机密提示器

func WithSecretResolver

func WithSecretResolver(resolver SecretResolver) Option

WithSecretResolver 配置机密解析器(传 nil 时回退到默认 fail-closed resolver)

type OutputMode

type OutputMode int

OutputMode 定义远程命令输出的收集策略。 注意:零值 OutputModeString 保持全量内存收集,这是为了向后兼容原有行为。 对于可能产生巨大输出的命令,调用方应显式指定其他模式以避免 OOM。

const (
	OutputModeString     OutputMode = iota // 默认,全量收集到内存(向后兼容)
	OutputModeRingBuffer                   // 环形缓冲,仅保留最后 N 字节
	OutputModeStream                       // 流式即时输出,不在内存中累积
	OutputModeFile                         // 直接写入文件,绕过内存
)

type PasswordAuth

type PasswordAuth struct {
	Password string
}

PasswordAuth 实现密码认证

func (*PasswordAuth) GetMethod

func (p *PasswordAuth) GetMethod() (ssh.AuthMethod, error)

type PlanConnection

type PlanConnection struct {
	Client *Client
	// contains filtered or unexported fields
}

PlanConnection leases one connection generation. Close releases this lease; it does not close transports still leased by another operation. Client is borrowed from the lease and must not outlive it.

func (*PlanConnection) Close

func (c *PlanConnection) Close() error

type PooledClient

type PooledClient struct {
	SSHClient *ssh.Client
	RootConn  net.Conn
	// contains filtered or unexported fields
}

PooledClient retains the outermost transport, including for ProxyJump clients. Interrupting it also terminates other clients sharing that transport.

type PrivilegeMaterial

type PrivilegeMaterial struct {
	Password []byte
	// contains filtered or unexported fields
}

PrivilegeMaterial 包含单次提权 (sudo/su) 所需的敏感机密材料。

func (*PrivilegeMaterial) Zero

func (p *PrivilegeMaterial) Zero()

Zero 清零敏感字节切片并清空引用。

type ProbeResult

type ProbeResult struct {
	DetectedDialect        LaunchDialect   `json:"detectedDialect" yaml:"detected_dialect"`
	AvailableInterpreters  []Interpreter   `json:"availableInterpreters" yaml:"available_interpreters"`
	RecommendedInterpreter Interpreter     `json:"recommendedInterpreter" yaml:"recommended_interpreter"`
	SuggestedConfig        ExecutionConfig `json:"suggestedConfig" yaml:"suggested_config"`
	RemoteOS               string          `json:"remoteOS" yaml:"remote_os"`
	RemoteShellPath        string          `json:"remoteShellPath" yaml:"remote_shell_path"`
	ServerVersion          string          `json:"serverVersion" yaml:"server_version"`
	Duration               time.Duration   `json:"duration" yaml:"duration"`
	ProbedAt               time.Time       `json:"probedAt" yaml:"probed_at"`
}

ProbeResult is a diagnostic snapshot. SuggestedConfig is safe to persist only when ProbeExecutionConfig returns no error. Unknown results preserve server passthrough semantics. Banner and shell path are metadata, never commands.

type ProxyCycleError

type ProxyCycleError struct {
	NodeID string
	Path   []string
}

ProxyCycleError 封装代理跳板环路错误

func (*ProxyCycleError) Error

func (e *ProxyCycleError) Error() string

func (*ProxyCycleError) Is

func (e *ProxyCycleError) Is(target error) bool

Is 支持与 auth.ErrProxyCycle 及 ErrProxyCycle 匹配

type RunConfig

type RunConfig struct {
	Interpreter   Interpreter
	LaunchDialect LaunchDialect
	LoginShell    bool
	OutMode       OutputMode
	RingMaxBytes  int
	StreamPrefix  string
	StreamWriter  io.Writer
	OutFile       *os.File
	// contains filtered or unexported fields
}

func DefaultRunConfig

func DefaultRunConfig() *RunConfig

type RunOption

type RunOption func(*RunConfig)

func WithInterpreter

func WithInterpreter(interp Interpreter) RunOption

func WithLaunchDialect

func WithLaunchDialect(dialect LaunchDialect) RunOption

WithLaunchDialect carries the frozen outer shell through legacy run adapters.

func WithLoginShell

func WithLoginShell(login bool) RunOption

func WithOutFile

func WithOutFile(file *os.File) RunOption

func WithOutputMode

func WithOutputMode(mode OutputMode) RunOption

func WithRingBuffer

func WithRingBuffer(maxBytes int) RunOption

func WithStream

func WithStream(writer io.Writer, prefix string) RunOption

type SSHProxyDialer

type SSHProxyDialer struct {
	Client *ssh.Client
	// RootConn is the outermost transport, shared by every hop in the chain.
	// Retaining it lets cancellation abort nested reads without a peer response.
	RootConn net.Conn
}

SSHProxyDialer 实现了 Dialer 接口,通过 SSH 隧道转发流量

func (*SSHProxyDialer) Dial

func (s *SSHProxyDialer) Dial(network, addr string) (net.Conn, error)

func (*SSHProxyDialer) DialContext

func (s *SSHProxyDialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error)

type SecretKind

type SecretKind uint8

SecretKind 标识需要交互输入的机密类型

const (
	SecretKindUnknown SecretKind = iota
	SecretKindLoginPassword
	SecretKindPrivateKeyPassphrase
	SecretKindSuPassword
	SecretKindSudoPassword
)

type SecretPrompter

type SecretPrompter interface {
	PromptSecret(ctx context.Context, request SecretRequest) (string, error)
}

SecretPrompter 负责提示用户输入敏感凭据(如密码、私钥密码短语等)

type SecretRequest

type SecretRequest struct {
	Kind         SecretKind
	NodeID       string
	User         string
	Host         string
	Port         int
	KeyPath      string
	VersionToken string
}

SecretRequest 描述向解析器或用户请求机密的上下文信息(严禁携带已有密码)

type SecretResolver

type SecretResolver interface {
	// ResolveSecret 根据机密请求解析并返回机密字节
	ResolveSecret(ctx context.Context, req SecretRequest) ([]byte, error)
}

SecretResolver 解析指定节点认证或提权所需机密。

type ShebangInfo

type ShebangInfo struct {
	HasShebang  bool
	HasBOM      bool
	Supported   bool
	Interpreter Interpreter
	Dialect     LaunchDialect
	RawLine     string
}

ShebangInfo describes the result of parsing a script's shebang line.

func ParseShebang

func ParseShebang(data []byte) ShebangInfo

ParseShebang inspects the first line of script data and validates it against the supported shebang allowlist (sh, bash, zsh and fish paths or /usr/bin/env sh|bash|zsh|fish without additional arguments). Trailing CR is ignored for metadata parsing.

type SudoMode

type SudoMode string

SudoMode 定义了 SSH 连接执行命令时的提权方式

const (
	SudoModeRoot   SudoMode = "root"
	SudoModeSudo   SudoMode = "sudo"
	SudoModeSudoer SudoMode = "sudoer"
	SudoModeSu     SudoMode = "su"
	SudoModeNone   SudoMode = "none"
	SudoModeAuto   SudoMode = "auto"
)

type SystemMetrics

type SystemMetrics struct {
	CPUUsage     float64
	Cores        int
	MemTotal     uint64
	MemUsed      uint64
	MemUsage     float64
	Disks        []DiskMetric
	Uptime       string
	LoadAverage  string
	TopProcesses []string
}

SystemMetrics 给 TUI 展示用的整理后指标

Jump to

Keyboard shortcuts

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