ssh_svc

package
v1.11.0 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: GPL-3.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildAuthMethodsForProxyChain added in v1.11.0

func BuildAuthMethodsForProxyChain(authType, password, key, keyPassphrase string, privateKeyPaths []string) ([]ssh.AuthMethod, error)

func MakeHostKeyCallback

func MakeHostKeyCallback(host string, port int, verifyFn HostKeyVerifyFunc) ssh.HostKeyCallback

MakeHostKeyCallback 创建 SSH HostKeyCallback

Types

type ConnectConfig

type ConnectConfig struct {
	Host          string
	Port          int
	Username      string
	AuthType      string // password | key | keyboard-interactive
	Password      string
	Key           string   // PEM 格式私钥(直接传入)
	KeyPassphrase string   // 私钥密码(用于加密的私钥)
	PrivateKeys   []string // 私钥文件路径列表
	AssetID       int64
	Cols          int
	Rows          int
	OnData        func(sessionID string, data []byte) // 终端输出回调
	OnClosed      func(sessionID string)              // 关闭回调
	OnSync        func(sessionID string, state DirectorySyncState)

	// 进度回调(异步连接用),step: resolve/connect/auth/shell
	OnProgress func(step, message string)
	// 键盘交互认证回调
	OnAuthChallenge func(prompts []string, echo []bool) ([]string, error)

	// 跳板机: 已解析的链式连接配置(从叶子到根)
	JumpHosts []JumpHostEntry
	// 代理
	Proxy *asset_entity.ProxyConfig
	// 代理链:非空时优先于旧 JumpHosts/Proxy。
	ProxyChain []proxychain.Layer

	// 主机密钥校验回调(nil 则跳过校验)
	HostKeyVerifyFunc HostKeyVerifyFunc

	// KeepAliveIntervalSeconds 覆盖此连接的 SSH 空闲保活心跳间隔(秒)。
	// 0 = 跟随全局默认(sshtuning)。
	KeepAliveIntervalSeconds int

	// RestoreCwdOnReconnect 为该资产开启「重连恢复上次目录」时为真:连接建立后
	// 自动启用目录同步以持续追踪 cwd,并在 InitialWorkdir 非空时 cd 回上次目录。
	RestoreCwdOnReconnect bool
	// InitialWorkdir 仅在重连路径由前端携带上次已知 cwd;首次连接为空。
	// 实际是否恢复由 RestoreCwdOnReconnect 权威闸门决定。
	InitialWorkdir string
}

ConnectConfig SSH 连接配置

type DirectorySyncState added in v1.5.0

type DirectorySyncState struct {
	SessionID   string `json:"sessionId"`
	Cwd         string `json:"cwd,omitempty"`
	CwdKnown    bool   `json:"cwdKnown"`
	Shell       string `json:"shell,omitempty"`
	ShellType   string `json:"shellType,omitempty"`
	Supported   bool   `json:"supported"`
	PromptReady bool   `json:"promptReady"`
	PromptClean bool   `json:"promptClean"`
	Busy        bool   `json:"busy"`
	Status      string `json:"status"` // "initializing" | "ready" | "unsupported"
	LastError   string `json:"lastError,omitempty"`
}

DirectorySyncState 表示终端目录同步状态。

type HostKeyAction

type HostKeyAction int

HostKeyAction 主机密钥校验操作

const (
	HostKeyAcceptAndSave HostKeyAction = iota // 接受并记住
	HostKeyAcceptOnce                         // 仅本次接受
	HostKeyReject                             // 取消/拒绝
)

type HostKeyEvent

type HostKeyEvent struct {
	Host           string `json:"host"`
	Port           int    `json:"port"`
	KeyType        string `json:"keyType"`
	Fingerprint    string `json:"fingerprint"`
	IsChanged      bool   `json:"isChanged"`      // true=密钥已变更(危险)
	OldFingerprint string `json:"oldFingerprint"` // 变更时的旧指纹
}

HostKeyEvent 主机密钥校验事件

type HostKeyVerifyFunc

type HostKeyVerifyFunc func(event HostKeyEvent) HostKeyAction

HostKeyVerifyFunc 主机密钥校验回调,由调用方实现不同的交互方式

func AutoTrustFirstRejectChangeVerifyFunc

func AutoTrustFirstRejectChangeVerifyFunc() HostKeyVerifyFunc

AutoTrustFirstRejectChangeVerifyFunc AI agent 使用:首次自动信任,变更拒绝

type JumpHostEntry

type JumpHostEntry struct {
	Host       string
	Port       int
	Username   string
	AuthType   string
	Password   string
	Key        string
	Passphrase string
}

JumpHostEntry 跳板机连接信息

type Manager

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

Manager 管理所有 SSH 会话

func NewManager

func NewManager() *Manager

NewManager 创建会话管理器

func (*Manager) ActiveSessions

func (m *Manager) ActiveSessions() int

ActiveSessions 返回活跃会话数

func (*Manager) Connect

func (m *Manager) Connect(cfg ConnectConfig) (string, error)

Connect 建立 SSH 连接并启动 PTY 会话

func (*Manager) ConnectClient added in v1.11.0

func (m *Manager) ConnectClient(cfg ConnectConfig) (string, error)

ConnectClient 建立仅用于 SFTP/端口转发等非终端用途的 SSH 会话 ID。 它不创建 PTY 和 shell,但会注册到 Manager sessions,供 SFTP 服务按 sessionID 复用。

func (*Manager) Dial

func (m *Manager) Dial(cfg ConnectConfig) (*ssh.Client, []io.Closer, error)

Dial 仅建立 SSH 连接(不创建 PTY/Session),用于连接池等场景

func (*Manager) Disconnect

func (m *Manager) Disconnect(id string)

Disconnect 断开指定会话

func (*Manager) DisconnectAll

func (m *Manager) DisconnectAll()

DisconnectAll 断开所有会话

func (*Manager) GetSession

func (m *Manager) GetSession(id string) (*Session, bool)

GetSession 获取会话

func (*Manager) GetSessionSyncState added in v1.5.0

func (m *Manager) GetSessionSyncState(id string) (DirectorySyncState, error)

GetSessionSyncState 获取会话目录同步状态。

func (*Manager) ListActiveSessionIDsByAsset added in v1.7.0

func (m *Manager) ListActiveSessionIDsByAsset(assetID int64) []string

ListActiveSessionIDsByAsset 返回指定资产当前仍处于活跃态的 SSH 会话 ID。 external edit 只允许在“同一资产且候选唯一”时做受限重绑,因此这里刻意只暴露最小会话列表, 不把终端层的更多运行态细节泄漏到上层业务。

func (*Manager) NewSessionFrom

func (m *Manager) NewSessionFrom(existingSessionID string, cols, rows int,
	onData func(string, []byte), onClosed func(string), onSync func(string, DirectorySyncState)) (string, error)

NewSessionFrom 在已有会话的连接上创建新会话(用于分割窗格)

func (*Manager) TestConnection

func (m *Manager) TestConnection(ctx context.Context, cfg ConnectConfig) error

TestConnection 测试 SSH 连接(仅验证连通性,不创建会话)。 ctx 取消时函数立即返回 ctx.Err(),后台 dial 仍会跑到 10s 兜底超时并自行清理。

type Session

type Session struct {
	ID      string
	AssetID int64
	// contains filtered or unexported fields
}

Session 表示一个活跃的 SSH 终端会话

func (*Session) ChangeDirectory added in v1.5.0

func (s *Session) ChangeDirectory(targetPath string) error

ChangeDirectory 在终端提示符可用时切换目录,并等待 shell 确认结果。

func (*Session) ChangeDirectoryDirect added in v1.7.0

func (s *Session) ChangeDirectoryDirect(targetPath string) error

ChangeDirectoryDirect writes a cd command without requiring directory-sync prompt hooks. It is used when the caller already knows the absolute target path and only needs the interactive terminal to move there.

func (*Session) ChangeDirectoryTo added in v1.5.0

func (s *Session) ChangeDirectoryTo(targetPath, expectedPath string) error

ChangeDirectoryTo switches the terminal to targetPath and treats expectedPath as the canonical cwd reported by the remote shell after the change.

func (*Session) Client

func (s *Session) Client() *ssh.Client

Client 返回底层 SSH Client(用于 SFTP 等)

func (*Session) Close

func (s *Session) Close()

Close 关闭会话

func (*Session) DisableSync added in v1.5.0

func (s *Session) DisableSync()

DisableSync removes hooks from the running shell and flips state back to unsupported. Best-effort: if the stdin write fails, state is still cleared.

No frontend caller wires this up yet — kept for symmetry with EnableSync and as the entry point when an explicit "disable directory sync" toggle ships. If the toggle never lands, this and buildDisableSyncCommand can be dropped.

func (*Session) EnableSync added in v1.5.0

func (s *Session) EnableSync() (err error)

EnableSync injects the directory-sync hooks into the running interactive shell and waits for the init:pid marker. Idempotent: returns nil immediately if the session is already supported with a known shell PID.

On timeout (no marker within syncEnableTimeout), state is rolled back to Supported=false and a CodeTimeout error is returned. Callers should map that to a "please exit foreground program and retry" hint in the UI.

func (*Session) GetSyncState added in v1.5.0

func (s *Session) GetSyncState() DirectorySyncState

func (*Session) IsClosed

func (s *Session) IsClosed() bool

IsClosed 检查是否已关闭

func (*Session) Resize

func (s *Session) Resize(cols, rows int) error

Resize 调整终端尺寸

func (*Session) RestoreWorkingDirectory added in v1.10.0

func (s *Session) RestoreWorkingDirectory(dir string) error

RestoreWorkingDirectory moves the freshly-started shell into dir when dir is non-empty. Used on reconnect to land the user back where they were. An empty dir (cwd was never known — unsupported shell / sync not yet populated) is a no-op, not an error, so the reconnect just opens at the shell's home.

func (*Session) Write

func (s *Session) Write(data []byte) error

Write 向终端写入数据(用户输入)

Jump to

Keyboard shortcuts

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