ssh

package
v0.0.0-...-42aef7f Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 17 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ssh is a small SSH client for talking to freshly booted test machines.

It covers ephemeral key generation, waiting for a machine to accept connections, running commands, and transferring files. Caller commands are never retried. WaitReady may repeat its fixed, harmless execution probe.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func InsecureHostKey

func InsecureHostKey() ssh.HostKeyCallback

InsecureHostKey accepts any host key. It is only appropriate for machines created and destroyed by the same test run, whose host key cannot be known in advance. Callers must pass it explicitly.

Types

type Client

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

Client is a connected SSH client returned by Dial or WaitReady. Call Close when finished; operation cancellation does not close the shared connection. A Client must not be copied after first use.

Example
package main

import (
	"bytes"
	"context"
	"fmt"
	"log"
	"os"
	"strings"
	"time"

	remotessh "github.com/microsoft/storm/utils/ssh"
)

func main() {
	key, err := remotessh.GenerateKey()
	if err != nil {
		log.Fatal(err)
	}
	// Install key.AuthorizedKey when provisioning this disposable guest.
	cfg := remotessh.Config{
		Addr:             "192.0.2.10:22",
		User:             "tester",
		Auth:             key.Signer,
		HostKey:          remotessh.InsecureHostKey(),
		RetryAuthFailure: true,
	}
	bootCtx, stopBoot := context.WithTimeout(context.Background(), 3*time.Minute)
	client, err := remotessh.WaitReady(bootCtx, cfg, time.Second)
	stopBoot() // The established client is independent of bootCtx.
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	result, err := client.Run(ctx, "uname -r")
	if err != nil {
		log.Fatal(err)
	}
	if result.ExitCode != 0 {
		log.Fatalf("exit %d: %s", result.ExitCode, result.Stderr)
	}
	fmt.Print(string(result.Stdout))

	result, err = client.RunIO(ctx, "cat", strings.NewReader("input\n"), os.Stdout, os.Stderr)
	if err != nil {
		log.Fatal(err)
	}
	if result.ExitCode != 0 {
		log.Fatalf("streamed command exited %d", result.ExitCode)
	}
	if err := client.Upload(ctx, "/tmp/settings.json", strings.NewReader(`{"enabled":true}`)); err != nil {
		log.Fatal(err)
	}
	var release bytes.Buffer
	if err := client.Download(ctx, "/etc/os-release", &release); err != nil {
		log.Fatal(err)
	}
	fmt.Print(release.String())
}

func Dial

func Dial(ctx context.Context, cfg Config) (*Client, error)

Dial connects once. ctx covers the TCP connection and the SSH handshake. The returned client remains usable after ctx ends and must be closed by the caller. Config.HostKey must explicitly verify or accept the host key.

func WaitReady

func WaitReady(ctx context.Context, cfg Config, interval time.Duration) (*Client, error)

WaitReady retries Dial and the command "true" until both succeed or ctx ends. Config.SkipExecCheck disables the command probe. It checks SSH execution, not application/service readiness. No caller-supplied command is retried. Errors that waiting cannot fix (invalid configuration, a rejected host key and, unless Config.RetryAuthFailure is set, a rejected key) are returned at once. No connection is left open on failure. Use a bounded ctx; the returned client's lifetime is independent of it. Nonpositive intervals retry without a delay.

func (*Client) Close

func (c *Client) Close() error

Close closes the connection and all its sessions, releasing pending startup operations. It returns the underlying connection's close error.

func (*Client) Download

func (c *Client) Download(ctx context.Context, remotePath string, dst io.Writer) error

Download copies a remote file to dst. Config.SFTPCommand selects a custom server, such as a passwordless sudo command. dst remains caller-owned. Cancellation covers startup and reads without closing other sessions. File-open, copy, file-close and SFTP-close errors are returned.

func (*Client) Run

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

Run buffers command output. Nonzero remote exit statuses are returned in Result with a nil error. Transport and I/O errors remain wrapped for errors.As. Unavailable exit statuses are -1. Cancellation follows RunIO's session-only semantics; commands are never retried.

func (*Client) RunIO

func (c *Client) RunIO(ctx context.Context, command string, stdin io.Reader, stdout, stderr io.Writer) (Result, error)

RunIO streams command I/O without retaining output in Result. Nil streams mean EOF/discard. stdout and stderr are consumed concurrently; writes are serialized, so both may use the same writer. Commands are never retried.

Cancellation stops waiting during startup and execution without closing the shared connection. Pending negotiations are released when the peer responds or Client.Close is called. Remote process termination is not guaranteed. Caller streams are not closed; writers must not block indefinitely, and callers must unblock pending reads from stdin themselves when cancelling.

func (*Client) SudoSFTP

func (c *Client) SudoSFTP(serverPath ...string) (*SFTP, error)

SudoSFTP selects passwordless, non-interactive sudo for this handle only. With no argument, the first transfer discovers a standalone server in standard OpenSSH locations and caches the successful path per SSH client. PATH is not searched. Pass one absolute executable path, not a command, to bypass discovery.

Construction performs no remote I/O. Invalid paths or multiple arguments return an error. Client defaults are unchanged; failures never fall back to ordinary transfers. Hosts with only internal-sftp need a standalone server installed.

Example
package main

import (
	"context"
	"log"
	"os"
	"time"

	remotessh "github.com/microsoft/storm/utils/ssh"
	"golang.org/x/crypto/ssh"
	"golang.org/x/crypto/ssh/knownhosts"
)

func main() {
	privateKey, err := os.ReadFile("run-key")
	if err != nil {
		log.Fatal(err)
	}
	signer, err := ssh.ParsePrivateKey(privateKey)
	if err != nil {
		log.Fatal(err)
	}
	verifyHost, err := knownhosts.New("known_hosts")
	if err != nil {
		log.Fatal(err)
	}
	cfg := remotessh.Config{
		Addr:    "192.0.2.10:22",
		User:    "tester",
		Auth:    signer,
		HostKey: verifyHost,
	}
	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	client, err := remotessh.Dial(ctx, cfg)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()
	files, err := client.SudoSFTP()
	if err != nil {
		log.Fatal(err)
	}
	if err := files.Download(ctx, "/var/log/messages", os.Stdout); err != nil {
		log.Fatal(err)
	}
}

func (*Client) Upload

func (c *Client) Upload(ctx context.Context, remotePath string, src io.Reader) error

Upload writes src to a remote file owned by the SFTP server user with mode 0600, staging in a private directory before renaming. Atomic replacement requires the server's POSIX rename extension; without it, an existing destination causes an error. Replacement does not follow destination symlinks or preserve existing ownership/mode. An error after rename or a lost acknowledgment does not imply the destination is unchanged. Files and transfer sessions are closed, with close errors returned. src remains caller-owned; callers must unblock pending reads on cancellation. Abrupt disconnections can leave a private staging directory on the server.

func (*Client) WaitDisconnected

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

WaitDisconnected returns nil when the connection closes, locally or remotely, or ctx.Err() if waiting is cancelled. It does not probe or reconnect; a silent network failure may remain undetected until ctx expires.

Example
package main

import (
	"context"
	"errors"
	"log"
	"time"

	remotessh "github.com/microsoft/storm/utils/ssh"
	"golang.org/x/crypto/ssh"
)

func main() {
	key, err := remotessh.GenerateKey()
	if err != nil {
		log.Fatal(err)
	}
	// Install key.AuthorizedKey when provisioning this disposable guest.
	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	client, err := remotessh.Dial(ctx, remotessh.Config{
		Addr: "192.0.2.10:22", User: "tester", Auth: key.Signer,
		HostKey: remotessh.InsecureHostKey(),
	})
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	result, err := client.Run(ctx, "sudo -n reboot")
	var missing *ssh.ExitMissingError
	if err != nil && !errors.As(err, &missing) {
		log.Fatal(err)
	}
	if err == nil && result.ExitCode != 0 {
		log.Fatalf("reboot exited %d: %s", result.ExitCode, result.Stderr)
	}
	if err := client.WaitDisconnected(ctx); err != nil {
		log.Fatal(err)
	}
	// Reconnect with WaitReady and verify the guest booted; disconnect alone
	// does not prove a successful reboot.
}

type Config

type Config struct {
	// Addr is host:port.
	Addr string
	// User is the remote login name.
	User string
	// Auth is the required authentication key; other signer types are accepted.
	Auth ssh.Signer
	// HostKey is required.
	HostKey ssh.HostKeyCallback
	// DialTimeout bounds TCP dialing and the handshake together. Defaults to
	// 10 seconds; negative values are invalid.
	DialTimeout time.Duration
	// RetryAuthFailure makes WaitReady keep retrying when the server rejects
	// the key. Off by default so a wrong key fails fast. Turn it on for a
	// machine that may start accepting connections before it has installed the
	// authorized key.
	RetryAuthFailure bool
	// SkipExecCheck makes WaitReady check authentication only, for hosts such
	// as SFTP-only accounts that reject SSH command execution. Dial ignores it.
	SkipExecCheck bool
	// SFTPCommand starts a caller-selected SFTP server instead of the default
	// subsystem. For sudo transfers, prefer Client.SudoSFTP.
	// No command is retried.
	SFTPCommand string
}

Config describes how to connect.

type Key

type Key struct {
	// Signer authenticates connections through Config.Auth.
	Signer ssh.Signer
	// AuthorizedKey is the public key in authorized_keys format, newline-terminated.
	AuthorizedKey string
	// PEM is the OpenSSH-format private key.
	PEM []byte
}

Key is an in-memory key pair. Nothing is written to disk; callers decide whether to persist PEM (with mode 0600).

func GenerateKey

func GenerateKey() (*Key, error)

GenerateKey creates an in-memory ed25519 key pair. Install AuthorizedKey in the guest before connecting; check that its crypto policy permits ed25519.

type Result

type Result struct {
	// Stdout is captured by Run and nil for RunIO.
	Stdout []byte
	// Stderr is captured separately by Run and nil for RunIO.
	Stderr []byte
	// ExitCode is the remote exit status, or -1 if unavailable.
	ExitCode int
	// Signal is the remote termination signal, if any.
	Signal string
}

Result is the outcome of a command.

type SFTP

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

SFTP is a scoped sudo file-transfer handle returned by Client.SudoSFTP. It borrows its client's connection; each transfer owns its SFTP session, so the handle itself needs no Close call.

Example
package main

import (
	"context"
	"log"
	"os"
	"strings"
	"time"

	remotessh "github.com/microsoft/storm/utils/ssh"
)

func main() {
	key, err := remotessh.GenerateKey()
	if err != nil {
		log.Fatal(err)
	}
	// Install key.AuthorizedKey when provisioning this disposable guest.
	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	client, err := remotessh.Dial(ctx, remotessh.Config{
		Addr: "192.0.2.10:22", User: "tester", Auth: key.Signer,
		HostKey: remotessh.InsecureHostKey(),
	})
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	// An explicit path skips discovery; omitting it enables auto-discovery.
	files, err := client.SudoSFTP("/opt/ssh/sftp-server")
	if err != nil {
		log.Fatal(err)
	}
	if err := files.Upload(ctx, "/etc/example.json", strings.NewReader(`{"enabled":true}`)); err != nil {
		log.Fatal(err)
	}
	if err := files.Download(ctx, "/etc/example.json", os.Stdout); err != nil {
		log.Fatal(err)
	}
}

func (*SFTP) Download

func (s *SFTP) Download(ctx context.Context, remotePath string, dst io.Writer) error

Download downloads through sudo using the same ownership, cancellation and error semantics as Client.Download. Discovery runs within ctx and is not cached on error.

func (*SFTP) Upload

func (s *SFTP) Upload(ctx context.Context, remotePath string, src io.Reader) error

Upload sends src through sudo with Client.Upload's private staging and replacement semantics. The uploaded file is owned by sudo's target user. Discovery runs within ctx; src remains caller-owned.

Jump to

Keyboard shortcuts

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