sshexec

package
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Overview

Package sshexec 是 RelayMesh 的 SSH 执行后端的传输层:严格固定主机密钥的连接、会话执行、按主机复用的连接池, 以及在远端主机上启动 / 轮询 / 读取 / 取消「后台任务」的 POSIX 脚本。

本包不知道 Hub 的运行状态机、闸门和数据库:它只负责「安全地把一小段脚本送到一台已确认身份的主机上并取回结果」。 凭据的加密保存、授权与审计都在调用方(internal/terminal)。

Index

Constants

View Source
const (
	DefaultDialTimeout = 10 * time.Second
	// DefaultMaxOutput 是一次会话里每一路输出在内存中的上限:本包只运行短脚本,远端不应该返回大量数据。
	DefaultMaxOutput = 2 << 20
)

连接与执行的默认参数。

View Source
const (
	AuthPassword = "password"
	AuthKey      = "key"
)

认证方式。

View Source
const (
	LaunchErrHome   = "home"
	LaunchErrMkdir  = "mkdir"
	LaunchErrB64    = "b64"
	LaunchErrDecode = "decode"
	LaunchErrCwd    = "cwd"
	LaunchErrSpawn  = "spawn"
)

启动失败的原因(LaunchResult.Err)。

View Source
const (
	DefaultKeepAliveEvery  = 30 * time.Second
	DefaultKeepAliveMisses = 3
)

保活的默认参数:每 30 秒一次,连续 3 次没有应答就视为连接已断开。

View Source
const MaxChunkBytes = 256 << 10

MaxChunkBytes 是一次轮询在每一路上最多取回的原始字节数。

View Source
const RemoteShell = "sh -s"

RemoteShell 是执行脚本时使用的命令(脚本从 stdin 输入)。

Variables

View Source
var (
	ErrHostKeyMismatch = errors.New("主机密钥与已固定的不一致")
	ErrAuthFailed      = errors.New("SSH 认证失败")
	ErrUnreachable     = errors.New("无法连接到 SSH 主机")
	ErrPassphrase      = errors.New("私钥已加密,需要提供口令")
	ErrBadCredential   = errors.New("凭据格式无效")
	ErrBadAddress      = errors.New("地址无效")
	ErrTooLarge        = errors.New("远端返回的数据超过上限")
	ErrUnsupported     = errors.New("目标主机不是受支持的 POSIX 环境")
	ErrNoHostKey       = errors.New("没有固定的主机密钥,拒绝连接")
	ErrProtocol        = errors.New("远端返回了无法解析的内容")
	ErrConn            = errors.New("SSH 连接中断")
	// ErrViaGateway:这份规格属于经网关接入的主机(Spec.Via 非空),只能由网关出站连接,本进程不得直连。
	ErrViaGateway = errors.New("这台 SSH 主机经网关主机接入,不能由本机直连")
)

稳定的错误值:调用方用 errors.Is 判断,并映射成稳定的错误码。

Functions

func CancelCommand

func CancelCommand(runID string) (cmd string, stdin []byte, err error)

CancelCommand 生成取消脚本:对整个进程组先发 TERM,宽限约 3 秒后发 KILL。

func FactsCommand

func FactsCommand() (cmd string, stdin []byte)

FactsCommand 返回探测脚本。

func LaunchCommand

func LaunchCommand(sp LaunchSpec) (cmd string, stdin []byte, err error)

LaunchCommand 生成启动脚本。

func NormalizeAddr

func NormalizeAddr(raw string) (string, error)

NormalizeAddr 把管理员输入的地址规整成 host:port(默认 22 端口)。 拒绝 user@host、URL、空白与控制字符:用户名单独配置,目标 ID 之外的地址永远不会来自模型。

func ParseLocaleProbe

func ParseLocaleProbe(out []byte) (charmap, utf8 string)

ParseLocaleProbe 解析探测输出:对方当前的字符集,以及一个可用的 UTF-8 locale 名(没有则为空)。

func PollCommand

func PollCommand(sp PollSpec) (cmd string, stdin []byte, err error)

PollCommand 生成轮询脚本。

func ReadCommand

func ReadCommand(sp ReadSpec) (cmd string, stdin []byte, err error)

ReadCommand 生成读取脚本。

func SweepCommand

func SweepCommand(days int) (cmd string, stdin []byte, err error)

SweepCommand 生成清理脚本:删除已结束且超过 days 天的任务目录(仍在运行的不动)。

func ValidRemoteShell

func ValidRemoteShell(s string) bool

ValidRemoteShell 判断 shell 名称是否允许用于 SSH 主机。

func ValidRunID

func ValidRunID(id string) bool

ValidRunID 判断运行 ID 是否可以安全地出现在远端脚本里。

func ValidUser

func ValidUser(u string) bool

ValidUser 检查 SSH 用户名:只允许常见的登录名字符。

Types

type CancelResult

type CancelResult struct {
	Gone   bool // 任务目录不存在
	Done   bool // 命令已经自行结束
	NoPID  bool
	Killed bool // 宽限期后仍存活,被 KILL
	Termed bool // TERM 后退出
}

CancelResult 是取消脚本的输出。

func ParseCancel

func ParseCancel(out []byte) (CancelResult, error)

ParseCancel 解析取消输出。

type Client

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

Client 是一条已认证的 SSH 连接。

func Dial

func Dial(ctx context.Context, sp Spec, timeout time.Duration) (*Client, error)

Dial 建立到 sp 的连接:主机密钥必须与固定值逐字节一致,否则返回 ErrHostKeyMismatch。

func (*Client) Close

func (c *Client) Close() error

Close 关闭连接。

func (*Client) Exec

func (c *Client) Exec(ctx context.Context, cmd string, stdin []byte, maxOut int) (Result, error)

Exec 在新会话里运行 cmd,stdin 作为标准输入。非 0 退出码是正常结果(Result.Exit),不是错误。

func (*Client) OpenShell

func (c *Client) OpenShell(opts ShellOptions) (*Shell, error)

OpenShell 在已认证的连接上申请伪终端并启动登录 shell。成功后 Shell 接管这条连接;失败时连接已被关闭。

type Credential

type Credential struct {
	Kind       string `json:"kind"`
	Password   string `json:"password,omitempty"`
	PrivateKey string `json:"private_key,omitempty"`
	Passphrase string `json:"passphrase,omitempty"`
}

Credential 是连接一台主机所需的认证材料。它永远不应该被打印:String / GoString 都做了脱敏。

func ParseCredential

func ParseCredential(b []byte) (Credential, error)

ParseCredential 还原 Marshal 的输出(不做私钥解析,解析发生在真正连接时)。

func (Credential) GoString

func (c Credential) GoString() string

GoString 脱敏输出(%#v)。

func (Credential) Marshal

func (c Credential) Marshal() ([]byte, error)

Marshal 序列化成待密封的字节。

func (Credential) String

func (c Credential) String() string

String 脱敏输出,避免凭据经 %v / %+v 误入日志。

func (Credential) Validate

func (c Credential) Validate() error

Validate 检查凭据的格式(私钥会被真正解析一次,口令不对 / 缺失会被发现)。

type Facts

type Facts struct {
	OS, Arch, Host, Home, User string
	Setsid, Timeout, Bash, B64 bool
}

Facts 是目标主机的环境信息。

func ParseFacts

func ParseFacts(out []byte) (Facts, error)

ParseFacts 解析探测输出;不是 POSIX 环境(没有 uname)或缺少 base64 时返回 ErrUnsupported。

type HostKey

type HostKey struct {
	Type        string        // 例如 ssh-ed25519
	Key         ssh.PublicKey // 公钥本体
	Fingerprint string        // SHA256:xxxx(与 ssh-keygen -l 的输出一致)
}

HostKey 是被探测到 / 被固定的主机公钥。

func DecodeHostKey

func DecodeHostKey(s string) (*HostKey, error)

DecodeHostKey 还原 Encode 的输出。

func NewHostKey

func NewHostKey(k ssh.PublicKey) *HostKey

NewHostKey 由公钥生成描述。

func Probe

func Probe(ctx context.Context, addr string, timeout time.Duration) (*HostKey, error)

Probe 只做密钥交换,取得服务器的主机公钥,不发送任何认证信息。

func (*HostKey) Encode

func (h *HostKey) Encode() string

Encode 把公钥编码成可存库的文本(标准 base64)。

type LaunchResult

type LaunchResult struct {
	PID       int
	Shell     string
	Duplicate bool   // 任务目录已存在:脚本被重放,没有再次启动
	Err       string // 非空表示没有启动
}

LaunchResult 是启动脚本的输出。

func ParseLaunch

func ParseLaunch(out []byte) (LaunchResult, error)

ParseLaunch 解析启动输出。

type LaunchSpec

type LaunchSpec struct {
	RunID      string
	Command    string
	Shell      string // 空表示自动选择(bash,其次 sh)
	Cwd        string // 空表示家目录
	TimeoutSec int
}

LaunchSpec 是一次启动的参数。

type PollResult

type PollResult struct {
	Gone     bool   // 任务目录不存在(已被清理或从未创建)
	Problem  string // 脚本自身报告的问题(例如 home)
	PID      int
	Alive    bool
	ExitCode *int  // 运行器写出了退出码才有值
	Finished int64 // 结束时间(Unix 秒,主机时钟),未结束为 0
	OutSize  int64
	ErrSize  int64
	Out, Err []byte // 从请求的偏移起取回的新增内容
}

PollResult 是轮询的结果。

func ParsePoll

func ParsePoll(out []byte) (PollResult, error)

ParsePoll 解析轮询输出。

type PollSpec

type PollSpec struct {
	RunID    string
	OutOff   int64
	ErrOff   int64
	MaxBytes int // 每一路最多取回的字节数,缺省并限制为 MaxChunkBytes
}

PollSpec 是一次轮询的参数:从两路输出的指定偏移起取回新增内容。

type Pool

type Pool struct {
	DialTimeout time.Duration
	MaxSessions int           // 每台主机同时进行的会话数上限,默认 8
	IdleTimeout time.Duration // 连接空闲多久后被回收,默认 90 秒
	// contains filtered or unexported fields
}

Pool 按主机复用 SSH 连接,并限制每台主机上同时进行的会话数。

func (*Pool) Close

func (p *Pool) Close()

Close 关闭所有连接。

func (*Pool) Exec

func (p *Pool) Exec(ctx context.Context, key string, sp Spec, cmd string, stdin []byte, maxOut int) (Result, error)

Exec 在 key 对应的主机上运行 cmd。连接层面的失败(连接被对端关掉等)会用新连接重试一次; 因此调用方传入的脚本必须是幂等的。

func (*Pool) Forget

func (p *Pool) Forget(key string)

Forget 关闭并丢弃某台主机的连接(凭据 / 固定的主机密钥 / 地址变化,或主机被删除时调用)。

func (*Pool) Reap

func (p *Pool) Reap(now time.Time) int

Reap 回收空闲超过 IdleTimeout 的连接,返回回收数量。

type ReadResult

type ReadResult struct {
	Gone    bool
	Problem string
	Size    int64
	Data    []byte
}

ReadResult 是读取的结果。

func ParseRead

func ParseRead(out []byte) (ReadResult, error)

ParseRead 解析读取输出。

type ReadSpec

type ReadSpec struct {
	RunID  string
	Stream string // stdout | stderr
	Off    int64
	Max    int
}

ReadSpec 是读取某一路输出的一页的参数。

type Result

type Result struct {
	Stdout []byte
	Stderr []byte
	Exit   int
}

Result 是一次会话的结果。

type Shell

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

Shell 是一个已启动的交互式 shell。它拥有底层的 SSH 连接:使用者读完输出后必须调用 Close(会一并关闭连接)。

func (*Shell) Close

func (s *Shell) Close() error

Close 关闭会话与底层连接(幂等),并解除阻塞中的 Read / Write。

func (*Shell) Kill

func (s *Shell) Kill()

Kill 请求结束会话:先发 SIGHUP 并关闭输入,宽限期过后仍未结束则直接关闭连接。不阻塞。

func (*Shell) Read

func (s *Shell) Read(p []byte) (int, error)

Read 读取远端输出(伪终端已把 stderr 合并进来)。远端结束后返回 io.EOF; 如果结束原因是连接中断,会先把一行可见的提示作为输出送出,让回放里也留下原因。

func (*Shell) Resize

func (s *Shell) Resize(rows, cols uint16) error

Resize 通知远端窗口大小变化。

func (*Shell) Wait

func (s *Shell) Wait() ShellExit

Wait 阻塞到会话结束并返回结果;可重复调用。

func (*Shell) Write

func (s *Shell) Write(p []byte) (int, error)

Write 向远端写入输入。

type ShellExit

type ShellExit struct {
	// Code 是远端 shell 的退出码;被信号终止或连接丢失时为 -1。
	Code int
	// Signal 是远端报告的终止信号名(没有则为空)。
	Signal string
	// Lost 为 true 表示不是远端自己退出,而是连接中断(网络断开、保活无应答、被本地关闭除外)。
	Lost bool
	// Reason 在 Lost 时给出已净化的简短原因。
	Reason string
}

ShellExit 描述一个 shell 会话是如何结束的。

type ShellOptions

type ShellOptions struct {
	Term string
	Rows uint16
	Cols uint16
	// KeepAliveEvery <= 0 使用默认值;KeepAliveMisses <= 0 使用默认值。
	KeepAliveEvery  time.Duration
	KeepAliveMisses int
	// KeepAliveReplyWait <= 0 使用默认值(单次保活请求等待应答的上限)。
	KeepAliveReplyWait time.Duration
	// NoLocaleProbe 为 true 时不探测、也不下发字符集(默认会探测,见 localeProbeScript)。
	NoLocaleProbe bool
}

ShellOptions 是 OpenShell 的参数。零值使用默认值。

type Spec

type Spec struct {
	Addr    string
	User    string
	Cred    Credential
	HostKey *HostKey
	// Via 是承载网关的机器码:非空表示这台主机只能经那台网关出站连接,凭据也只保存在网关上。
	// 本包自身从不使用它,但 Dial 会拒绝 Via 非空的规格(ErrViaGateway)——「Hub 不得绕过网关自己去连」
	// 因此是底层保证,而不只是调用方的约定。
	Via string
}

Spec 描述如何连接一台主机。HostKey 必须有值:没有固定的主机密钥时拒绝连接。

func (Spec) String

func (s Spec) String() string

String 不含凭据。

Directories

Path Synopsis
Package sshdtest 提供一个只用于测试的进程内 SSH 服务器:支持密码 / 键盘交互 / 公钥认证, 对每个 exec 请求用本机的 /bin/sh -c 真正执行,并把 stdin 转给子进程。
Package sshdtest 提供一个只用于测试的进程内 SSH 服务器:支持密码 / 键盘交互 / 公钥认证, 对每个 exec 请求用本机的 /bin/sh -c 真正执行,并把 stdin 转给子进程。

Jump to

Keyboard shortcuts

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