ssh

package
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultPasswordPromptPattern = `` /* 126-byte string literal not displayed */

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

Variables

This section is empty.

Functions

func BuildAutoAuthMethods added in v0.5.0

func BuildAutoAuthMethods(user, host string, ui InteractionHandler, passwordCallback func(string), passphraseCallback func(keyPath, passphrase string)) ([]ssh.AuthMethod, func())

BuildAutoAuthMethods 生成一个包含多种回退机制的 AuthMethod 链 passphraseCallback 在用户成功输入受密码保护的私钥密码后被调用,用于持久化

func StartKeepAlive

func StartKeepAlive(ctx context.Context, client *ssh.Client, interval time.Duration, fallback func(err error))

StartKeepAlive 开启一个协程,定期向 SSH Server 发送心跳 ctx: 用于控制协程退出的上下文 interval: 心跳间隔 (建议 15s - 60s) fallback: 可选的回调函数,用于在心跳失败后执行,心跳失败时会关闭连接

func StaticRespond added in v0.9.0

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

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

Types

type AuthMethod

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

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

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

func (c *Client) Close() error

Close 关闭连接

func (*Client) Config added in v0.9.0

func (c *Client) Config() *ClientConfig

Config 返回当前连接对应的节点配置

func (*Client) LocalForward added in v0.5.0

func (c *Client) LocalForward(ctx context.Context, localAddr, remoteAddr string) 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) 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) RunInteractive added in v0.4.0

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

RunInteractive 在 PTY 环境下执行单条命令,支持交互式/流式命令 (如 tail -f, vim, top)

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

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

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

func (*Client) RunScript

func (c *Client) RunScript(ctx context.Context, scriptContent string, opts ...RunOption) (string, 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

SSHClient 暴露底层的 ssh.Client (供高级操作使用,如 SCP)

func (*Client) Shell

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

func (*Client) ShellWithSudo

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

func (*Client) Socks5Forward added in v0.10.0

func (c *Client) Socks5Forward(ctx context.Context, listenAddr string) 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
	SudoMode   SudoMode // "root", "sudo", "sudoer", "su", "none", "auto"
	SuPwd      string
	ProxyJump  string // 跳板机的 NodeID
	// PasswordPromptPattern 自定义密码提示正则(节点级,可选)。
	// 为空时回落到 Connector 的全局配置,再为空则使用内置的多语言默认模式。
	PasswordPromptPattern string
}

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

type ConfigStore added in v0.9.0

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

	// UpdateAuth 在 "auto" 模式下探测到可用密码或私钥 passphrase 时,写回持久化存储
	UpdateAuth(nodeID string, password, keyPath, passphrase string) error

	// UpdateSudo 在探测到可用提权模式或接收到 su 密码时,写回持久化存储
	UpdateSudo(nodeID string, mode SudoMode, suPwd string) error
}

ConfigStore 定义底层如何获取配置以及如何回写探测到的新配置。

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(store ConfigStore, ui InteractionHandler) *Connector

NewConnector 创建一个新的 Connector

func (*Connector) CloseAll

func (c *Connector) CloseAll()

CloseAll 关闭所有缓存的连接 (在程序退出前调用)

func (*Connector) Connect

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

Connect 根据节点名称建立 SSH 连接 自动处理跳板机逻辑:如果节点配置了 ProxyJump,会递归建立连接

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

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

type InteractionHandler interface {
	// PromptPassword 提示用户输入密码(例如常规密码或 su 密码)
	PromptPassword(prompt string) (string, error)

	// ConfirmHostKey 提示用户确认未知的 HostKey,返回是否同意连接
	ConfirmHostKey(hostname string, fingerprint string) (bool, error)
}

InteractionHandler 定义应用层(CLI 或 GUI)所需实现的交互式输入接口。

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

func (*MetricsCollector) NextFrame added in v0.8.0

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

func (*MetricsCollector) Start added in v0.8.0

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

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