sshclient

package
v0.0.12 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultSSHPort    = "22"
	DefaultSSHUser    = "master"
	DefaultSudoKey    = "master"
	DefaultTimeout    = 30 * time.Second
	SudoPrompt        = "[sudo] password"
	PasswordPromptEnd = ": "
)
View Source
const KeyringServiceName = "sshx"
View Source
const MaxCaptureBytes = 10 << 20 // 10 MiB

MaxCaptureBytes bounds how much stdout/stderr is buffered in capture mode so a runaway command cannot exhaust memory.

Variables

View Source
var (
	// ErrCommandTimeout indicates the command exceeded the configured timeout.
	ErrCommandTimeout = errors.New("command execution timed out")
	// ErrNoExitStatus indicates the remote closed the session without reporting
	// an exit status (for example, the command was terminated by a signal).
	ErrNoExitStatus = errors.New("remote command terminated without exit status")
)

Functions

func CommandUsesSudo added in v0.0.10

func CommandUsesSudo(command string) bool

CommandUsesSudo reports whether sshx can safely treat the command as a sudo command for password auto-fill. Only a leading sudo command is supported, because that is the only form sudoStdinCommand can rewrite without guessing at shell syntax.

func GetSudoPassword

func GetSudoPassword(key string) (string, error)

GetSudoPassword reads sudo password from system keyring (cross-platform support) macOS: Keychain, Linux: Secret Service (gnome-keyring/kwallet), Windows: Credential Manager

func ValidateCommand

func ValidateCommand(command string) error

ValidateCommand performs a best-effort safety check against a small set of well-known destructive commands (for example "rm -rf /" or a fork bomb).

It is a guardrail to catch accidental mistakes, NOT a security boundary: the substring/keyword matching is trivially bypassed (casing, quoting, shell variables, alternate paths), so it must never be relied upon to sandbox untrusted input.

Types

type AuthMethod added in v0.0.10

type AuthMethod string

AuthMethod indicates which authentication mechanism was used for the SSH connection.

const (
	AuthMethodUnknown          AuthMethod = "unknown"
	AuthMethodKey              AuthMethod = "key"
	AuthMethodPassword         AuthMethod = "password"
	AuthMethodPasswordFallback AuthMethod = "password-fallback"
)

type CommandBlockedError added in v0.0.10

type CommandBlockedError struct {
	Command string
	Reason  string
}

CommandBlockedError is returned by ValidateCommand when a command matches a known destructive pattern. Its message is unchanged from the previous plain error so existing output and substring checks keep working, while callers can now detect a safety block via errors.As.

func (*CommandBlockedError) Error added in v0.0.10

func (e *CommandBlockedError) Error() string

type Config

type Config struct {
	Host        string
	Port        string
	User        string
	Password    string
	KeyPath     string
	UseKeyAuth  bool
	SudoKey     string
	Command     string
	Mode        string
	DialTimeout time.Duration
	// Timeout bounds the execution of a single remote command. Zero means no
	// command timeout (the dial timeout still applies).
	Timeout time.Duration
	// JSONOutput emits a single structured JSON result instead of streaming
	// human-readable output. It implies clean, separated stdout/stderr capture.
	JSONOutput bool
	// UsePTY requests a pseudo-terminal for command execution. It is off by
	// default because a PTY merges stderr into stdout and injects terminal
	// control characters; it is ignored in JSON/capture mode.
	UsePTY bool
	// DryRun emits a local execution plan without connecting, executing, reading
	// keyring secrets, or mutating local/remote state.
	DryRun bool
	// AuditEnabled controls whether sshx writes a local structured audit event.
	AuditEnabled bool
	// AuditOutput overrides the directory where audit JSONL files are written.
	AuditOutput string

	SafetyCheck bool
	Force       bool
	// AcceptUnknownHost controls whether sshx will automatically add
	// previously unseen host keys to the user's known_hosts file.
	AcceptUnknownHost bool
	// AllowInsecureHostKey controls whether sshx may fall back to
	// ssh.InsecureIgnoreHostKey (legacy behavior). Disabled by default.
	AllowInsecureHostKey bool
	// KnownHostsPath allows overriding the path to the known_hosts file.
	KnownHostsPath string

	SftpAction string
	LocalPath  string
	RemotePath string

	PasswordAction string
	PasswordKey    string
	PasswordValue  string

	// Host management fields
	HostAction      string
	HostName        string
	HostDescription string
	HostType        string
}

Config represents SSH configuration properties for connecting to remote hosts.

type ExecResult added in v0.0.10

type ExecResult struct {
	ExitCode        int
	Stdout          string
	Stderr          string
	StdoutTruncated bool
	StderrTruncated bool
}

ExecResult captures the outcome of running a remote command.

type SSHClient

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

SSHClient wraps an ssh.Client with optional pooled and sftp helpers.

func NewSSHClient

func NewSSHClient(config *Config) (*SSHClient, error)

NewSSHClient 创建SSH客户端

func (*SSHClient) AuthMethodUsed added in v0.0.10

func (c *SSHClient) AuthMethodUsed() AuthMethod

AuthMethodUsed returns the authentication method used for the current connection.

func (*SSHClient) Close

func (c *SSHClient) Close() error

Close closes the SFTP and SSH connections.

func (*SSHClient) ConnectDirect added in v0.0.10

func (c *SSHClient) ConnectDirect() error

ConnectDirect establishes a direct SSH connection.

func (*SSHClient) ExecuteCommandWithOutput

func (c *SSHClient) ExecuteCommandWithOutput() (output string, err error)

ExecuteCommandWithOutput executes a command and returns the output

func (*SSHClient) ExecuteSftp

func (c *SSHClient) ExecuteSftp() (err error)

ExecuteSftp executes SFTP operations

func (*SSHClient) ForceClose

func (c *SSHClient) ForceClose() error

ForceClose forcefully closes the underlying SSH connection.

func (*SSHClient) RunCommand added in v0.0.10

func (c *SSHClient) RunCommand(capture bool) (ExecResult, error)

RunCommand executes the configured command and returns a structured result.

When capture is true, stdout and stderr are buffered separately (used for --json output). When capture is false they stream live to os.Stdout and os.Stderr on independent channels with no PTY, which keeps output clean and machine-parseable. A PTY is only requested when UsePTY is set and capture is false; note that a PTY merges stderr into stdout.

The returned error is non-nil only for sshx-level failures (validation, session setup, timeout, or an abnormal teardown). A remote command that exits non-zero is NOT an error here: the status is reported in ExecResult.ExitCode with a nil error.

Jump to

Keyboard shortcuts

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