ssh

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultKeepAliveInterval = 15 * time.Second
	DefaultKeepAliveTimeout  = 10 * time.Second
)

心跳默认参数:间隔 15s 对齐 OpenSSH ServerAliveInterval 推荐值; 单次探测超时 10s,超时即判定网络不可达(覆盖网络黑洞场景)

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 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 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 完全退出后关闭,调用方可据此等待资源回收。

func StaticRespond added in v0.9.0

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

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

Types

type AuthMaterial added in v0.12.0

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

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

func (*AuthMaterial) Zero added in v0.12.0

func (a *AuthMaterial) Zero()

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

type AuthMethod

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

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

type AutoAuthOptions added in v0.12.0

type AutoAuthOptions struct {
	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 added in v0.8.0

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 added in v0.8.0

func (t *CPUTicks) IdleTicks() uint64

func (*CPUTicks) Total added in v0.8.0

func (t *CPUTicks) Total() uint64

type Client

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

func (*Client) AuthMaterial added in v0.12.0

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) Close

func (c *Client) Close() error

func (*Client) Config added in v0.9.0

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 added in v0.12.0

func (c *Client) ConnectionConfig() ConnectionConfig

ConnectionConfig returns a copy of the live connection configuration.

func (*Client) Interrupt added in v0.12.0

func (c *Client) Interrupt() error

Interrupt closes the underlying transport forcefully and synchronously. It sets an immediate deadline on rootConn and closes the network connection, unblocking any concurrent I/O operations without spawning background goroutines.

func (*Client) LocalForward added in v0.5.0

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) RemoteForward added in v0.5.0

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.

func (*Client) Run

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

func (*Client) RunCommandWithIO added in v0.12.0

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 added in v0.12.0

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 added in v0.4.0

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 added in v0.6.0

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

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

func (*Client) RunInteractiveCmdWithIO added in v0.12.0

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

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

func (*Client) RunInteractiveWithSudo added in v0.4.0

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

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

func (*Client) RunInteractiveWithSudoIO added in v0.12.0

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) RunScriptWithSudo

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

RunScriptWithSudo 提权执行脚本

func (*Client) RunStream added in v0.8.0

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) 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 added in v0.12.0

func (c *Client) ShellWithIO(ctx context.Context, streams InteractiveIO) (retErr 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 added in v0.12.0

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

ShellWithSudoIO authenticates before switching the local terminal to raw mode.

func (*Client) Socks5Forward added in v0.10.0

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.

type ClientConfig added in v0.9.0

type ClientConfig struct {
	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
}

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

func (*ClientConfig) ToConnectionConfig added in v0.12.0

func (c *ClientConfig) ToConnectionConfig() ConnectionConfig

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

type ConfigStore added in v0.9.0

type ConfigStore interface {
	ConnectionProvider
	CredentialRecorder
}

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

type ConnectionConfig added in v0.12.0

type ConnectionConfig struct {
	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
}

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

type ConnectionError added in v0.12.0

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

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

func (*ConnectionError) Error added in v0.12.0

func (e *ConnectionError) Error() string

func (*ConnectionError) Unwrap added in v0.12.0

func (e *ConnectionError) Unwrap() error

type ConnectionProvider added in v0.12.0

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) EnableKeepAlive added in v0.12.0

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

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

type CredentialFailureReporter added in v0.12.0

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 added in v0.12.0

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 added in v0.8.0

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

DiskMetric 存储单个分区的指标

type Expect added in v0.9.0

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

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

func NewExpect added in v0.9.0

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

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

func NewExpectWithOptions added in v0.12.0

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

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

func (*Expect) CleanOutput added in v0.9.0

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

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

func (*Expect) Output added in v0.9.0

func (e *Expect) Output() string

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

func (*Expect) SetAccumulate added in v0.9.0

func (e *Expect) SetAccumulate(acc bool)

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

func (*Expect) SetTarget added in v0.9.0

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

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

func (*Expect) Stop added in v0.9.0

func (e *Expect) Stop()

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

func (*Expect) Wait added in v0.9.0

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

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

func (*Expect) Write added in v0.9.0

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

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

type ExpectOption added in v0.12.0

type ExpectOption func(*Expect)

ExpectOption 用于配置 Expect

func WithExpectLogger added in v0.12.0

func WithExpectLogger(l logger.DebugLogger) ExpectOption

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

type ExpectRule added in v0.9.0

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

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

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

type Forward added in v0.12.0

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) Wait added in v0.12.0

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 added in v0.12.0

type ForwardOption func(*forwardOptions)

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

func WithForwardErrorHandler added in v0.12.0

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 added in v0.12.0

type HandshakeError struct {
	NodeID string
	Err    error
}

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

func (*HandshakeError) Error added in v0.12.0

func (e *HandshakeError) Error() string

func (*HandshakeError) Unwrap added in v0.12.0

func (e *HandshakeError) Unwrap() error

type HostKeyConfirmation added in v0.12.0

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

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

type HostKeyConfirmer added in v0.12.0

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

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

type InteractionHandler added in v0.9.0

type InteractionHandler interface {
	SecretPrompter
	HostKeyConfirmer
}

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

type InteractiveIO added in v0.12.0

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 KeyAuth

type KeyAuth struct {
	Path       string
	Passphrase string
}

KeyAuth 实现私钥认证

func (*KeyAuth) GetMethod

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

type LockedWriter added in v0.10.0

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

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

func NewLockedWriter added in v0.10.0

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

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

func (*LockedWriter) Write added in v0.10.0

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

type MetricsCollector added in v0.8.0

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

func NewMetricsCollector added in v0.8.0

func NewMetricsCollector(c *Client) *MetricsCollector

func (*MetricsCollector) Close added in v0.8.0

func (mc *MetricsCollector) Close() error

func (*MetricsCollector) NextFrame added in v0.8.0

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

func (*MetricsCollector) SortConfig added in v0.12.0

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

SortConfig returns a stable snapshot of display ordering preferences.

func (*MetricsCollector) Start added in v0.8.0

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

func (*MetricsCollector) ToggleSortBy added in v0.12.0

func (mc *MetricsCollector) ToggleSortBy()

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

func (*MetricsCollector) ToggleSortOrder added in v0.12.0

func (mc *MetricsCollector) ToggleSortOrder()

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

type Option added in v0.12.0

type Option func(*Connector)

Option 用于配置 Connector

func WithConnectionProvider added in v0.12.0

func WithConnectionProvider(provider ConnectionProvider) Option

WithConnectionProvider 配置连接配置提供者

func WithCredentialRecorder added in v0.12.0

func WithCredentialRecorder(recorder CredentialRecorder) Option

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

func WithDialer added in v0.12.0

func WithDialer(dialer Dialer) Option

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

func WithHandshakeTimeout added in v0.12.0

func WithHandshakeTimeout(timeout time.Duration) Option

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

func WithHostKeyConfirmer added in v0.12.0

func WithHostKeyConfirmer(confirmer HostKeyConfirmer) Option

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

func WithInteractionHandler added in v0.12.0

func WithInteractionHandler(handler InteractionHandler) Option

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

func WithInteractionTimeout added in v0.12.0

func WithInteractionTimeout(timeout time.Duration) Option

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

func WithLogger added in v0.12.0

func WithLogger(l logger.DebugLogger) Option

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

func WithPasswordPromptPattern added in v0.12.0

func WithPasswordPromptPattern(pattern string) Option

WithPasswordPromptPattern 配置密码匹配正则

func WithSecretPrompter added in v0.12.0

func WithSecretPrompter(prompter SecretPrompter) Option

WithSecretPrompter 单独配置机密提示器

func WithSecretResolver added in v0.12.0

func WithSecretResolver(resolver SecretResolver) Option

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

type OutputMode added in v0.10.0

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 PooledClient added in v0.12.0

type PooledClient struct {
	SSHClient *ssh.Client
	RootConn  net.Conn
}

PooledClient represents a pooled SSH client with its underlying connection

type PrivilegeMaterial added in v0.12.0

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

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

func (*PrivilegeMaterial) Zero added in v0.12.0

func (p *PrivilegeMaterial) Zero()

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

type ProxyCycleError added in v0.12.0

type ProxyCycleError struct {
	NodeID string
	Path   []string
}

ProxyCycleError 封装代理跳板环路错误

func (*ProxyCycleError) Error added in v0.12.0

func (e *ProxyCycleError) Error() string

func (*ProxyCycleError) Is added in v0.12.0

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

Is 支持与 config.ErrProxyCycle 及 ErrProxyCycle 匹配

type RunConfig added in v0.9.0

type RunConfig struct {
	LoginShell   bool
	OutMode      OutputMode
	RingMaxBytes int
	StreamPrefix string
	StreamWriter io.Writer
	OutFile      *os.File
}

func DefaultRunConfig added in v0.9.0

func DefaultRunConfig() *RunConfig

type RunOption added in v0.9.0

type RunOption func(*RunConfig)

func WithLoginShell added in v0.9.0

func WithLoginShell(login bool) RunOption

func WithOutFile added in v0.10.0

func WithOutFile(file *os.File) RunOption

func WithOutputMode added in v0.10.0

func WithOutputMode(mode OutputMode) RunOption

func WithRingBuffer added in v0.10.0

func WithRingBuffer(maxBytes int) RunOption

func WithStream added in v0.10.0

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

type SSHProxyDialer

type SSHProxyDialer struct {
	Client *ssh.Client
}

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 added in v0.12.0

type SecretKind uint8

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

const (
	SecretKindUnknown SecretKind = iota
	SecretKindLoginPassword
	SecretKindPrivateKeyPassphrase
	SecretKindSuPassword
	SecretKindSudoPassword
)

type SecretPrompter added in v0.12.0

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

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

type SecretRequest added in v0.12.0

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

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

type SecretResolver added in v0.12.0

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

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

type SudoMode added in v0.9.0

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 added in v0.8.0

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