ssh

package
Version: v0.0.0-...-2c994ed Latest Latest
Warning

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

Go to latest
Published: May 8, 2021 License: BSD-3-Clause Imports: 18 Imported by: 0

Documentation

Overview

Package ssh provides means to communicate with remote host through SSH.

Index

Constants

This section is empty.

Variables

View Source
var DefaultPlatform = &Platform{BuildShellCommand: shellCmd}

DefaultPlatform represents a system with a generic POSIX shell.

Functions

func ParseTarget

func ParseTarget(target string, o *Options) error

ParseTarget parses target (of the form "[<user>@]host[:<port>]") and fills the User, Hostname, and Port fields in o, using reasonable defaults for unspecified values.

Types

type Cmd

type Cmd struct {
	// Args holds command line arguments, including the command as Args[0].
	Args []string

	// Dir specifies the working directory of the command.
	// If Dir is the empty string, Run runs the command in the default directory,
	// typically the home directory of the SSH user.
	Dir string

	// Stdin specifies the process's standard input.
	Stdin io.Reader

	// Stdout specifies the process's standard output.
	Stdout io.Writer

	// Stderr specifies the process's standard error.
	Stderr io.Writer
	// contains filtered or unexported fields
}

Cmd represents an external command being prepared or run on a remote host.

This type implements almost similar interface to os/exec, but there are several notable differences.

Command does not accept context.Context, but Cmd's methods do. This is to support existing use cases where we want to use different deadlines for different operations (e.g. Start and Wait) on the same command execution.

func (*Cmd) Abort

func (c *Cmd) Abort()

Abort requests to abort the command execution.

This method does not block, but you still need to call Wait. It is safe to call this method while calling Wait/Run/Output/CombinedOutput in another goroutine. After calling this method, Wait/Run/Output/CombinedOutput will return immediately. This method can be called at most once.

func (*Cmd) CombinedOutput

func (c *Cmd) CombinedOutput(ctx context.Context, opts ...RunOption) ([]byte, error)

CombinedOutput runs the command and returns its combined standard output and standard error.

The command is aborted when ctx's deadline is reached.

See: https://godoc.org/os/exec#Cmd.CombinedOutput

func (*Cmd) DumpLog

func (c *Cmd) DumpLog(ctx context.Context) error

DumpLog logs details of the executed external command, including uncaptured output.

This function must be called after Wait.

func (*Cmd) Output

func (c *Cmd) Output(ctx context.Context, opts ...RunOption) ([]byte, error)

Output runs the command and returns its standard output.

The command is aborted when ctx's deadline is reached.

See: https://godoc.org/os/exec#Cmd.Output

func (*Cmd) Run

func (c *Cmd) Run(ctx context.Context, opts ...RunOption) error

Run starts the specified command and waits for it to complete.

The command is aborted when ctx's deadline is reached.

See: https://godoc.org/os/exec#Cmd.Run

func (*Cmd) Start

func (c *Cmd) Start(ctx context.Context) error

Start starts the specified command but does not wait for it to complete.

The command is aborted when ctx's deadline is reached.

See: https://godoc.org/os/exec#Cmd.Start

func (*Cmd) StderrPipe

func (c *Cmd) StderrPipe() (io.ReadCloser, error)

StderrPipe returns a pipe that will be connected to the command's standard error when the command starts.

The returned pipe is closed automatically when the context deadline is reached, Abort is called, or Wait/Run/Output/CombinedOutput sees the command exit. Thus it is incorrect to call Wait while reading from the pipe, or to use StderrPipe with Run/Output/CombinedOutput. See the os/exec documentation for details.

See: https://godoc.org/os/exec#Cmd.StderrPipe

func (*Cmd) StdinPipe

func (c *Cmd) StdinPipe() (io.WriteCloser, error)

StdinPipe returns a pipe that will be connected to the command's standard input when the command starts.

Close the pipe to send EOF to the remote process.

Important difference with os/exec:

The returned pipe is NOT closed automatically. Wait/Run/Output/CombinedOutput may block until you close the pipe explicitly.

See: https://godoc.org/os/exec#Cmd.StdinPipe

func (*Cmd) StdoutPipe

func (c *Cmd) StdoutPipe() (io.ReadCloser, error)

StdoutPipe returns a pipe that will be connected to the command's standard output when the command starts.

The returned pipe is closed automatically when the context deadline is reached, Abort is called, or Wait/Run/Output/CombinedOutput sees the command exit. Thus it is incorrect to call Wait while reading from the pipe, or to use StdoutPipe with Run/Output/CombinedOutput. See the os/exec documentation for details.

See: https://godoc.org/os/exec#Cmd.StdoutPipe

func (*Cmd) Wait

func (c *Cmd) Wait(ctx context.Context, opts ...RunOption) error

Wait waits for the command to exit and waits for any copying to stdin or copying from stdout or stderr to complete.

This method can be called only if the command was started by Start. It is an error to call this method multiple times, but it will not panic as long as it is not called in parallel.

The command is aborted when ctx's deadline is reached. Note that the deadline of the context passed to Start also applies.

See: https://godoc.org/os/exec#Cmd.Wait

type Conn

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

Conn represents an SSH connection to another computer.

func New

func New(ctx context.Context, o *Options) (*Conn, error)

New establishes an SSH connection to the host described in o. Callers are responsible to call Conn.Close after using it.

func (*Conn) Close

func (s *Conn) Close(ctx context.Context) error

Close closes the underlying connection to the host.

func (*Conn) Command

func (s *Conn) Command(name string, args ...string) *Cmd

Command returns the Cmd struct to execute the named program with the given arguments.

It is fine to call this method with nil receiver; subsequent method calls will just fail.

See: https://godoc.org/os/exec#Command

func (*Conn) ForwardLocalToRemote

func (s *Conn) ForwardLocalToRemote(network, localAddr, remoteAddr string, errFunc func(error)) (*Forwarder, error)

ForwardLocalToRemote creates a new Forwarder that forwards connections from localAddr to remoteAddr using s. network is passed to net.Listen. Only TCP networks are supported. localAddr is passed to net.Listen and typically takes the form "host:port" or "ip:port". remoteAddr uses the same format but is resolved by the remote SSH server. If non-nil, errFunc will be invoked asynchronously on a goroutine with connection or forwarding errors.

func (*Conn) ForwardRemoteToLocal

func (s *Conn) ForwardRemoteToLocal(network, remoteAddr, localAddr string, errFunc func(error)) (*Forwarder, error)

ForwardRemoteToLocal creates a new Forwarder that forwards connections from DUT to localaddr. network is passed to net.Dial. Only TCP networks are supported. remoteAddr is resolved by the remote SSH server and typically takes the form "host:port" or "ip:port". localAddr takes the same format but is passed to net.Listen on the local machine. If non-nil, errFunc will be invoked asynchronously on a goroutine with connection or forwarding errors.

func (*Conn) ListenTCP

func (s *Conn) ListenTCP(addr *net.TCPAddr) (net.Listener, error)

ListenTCP opens a remote TCP port for listening.

func (*Conn) NewForwarder

func (s *Conn) NewForwarder(localAddr, remoteAddr string, errFunc func(error)) (*Forwarder, error)

NewForwarder creates a new Forwarder that forwards connections from localAddr to remoteAddr using s. Deprecated. Use ForwardLocalToRemote instead for naming consistency.

func (*Conn) Ping

func (s *Conn) Ping(ctx context.Context, timeout time.Duration) error

Ping checks that the connection to the host is still active, blocking until a response has been received. An error is returned if the connection is inactive or if timeout or ctx's deadline are exceeded.

type Forwarder

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

Forwarder creates a listener that forwards TCP connections to another host over an already-established SSH connection.

A pictoral explanation:

               Local               |    SSH Host    |   Remote
-----------------------------------+----------------+-------------

(local-to-remote)

[client] <- TCP -> [Forwarder] <- SSH -> [sshd] <- TCP -> [server]

(remote-to-local)

[server] <- TCP -> [Forwarder] <- SSH -> [sshd] <- TCP -> [client]

func (*Forwarder) Close

func (f *Forwarder) Close() error

Close stops listening for incoming connections.

func (*Forwarder) ListenAddr

func (f *Forwarder) ListenAddr() net.Addr

ListenAddr returns the address used to listen for connections.

func (*Forwarder) LocalAddr

func (f *Forwarder) LocalAddr() net.Addr

LocalAddr returns the address used to listen for connections. Deprecated. Use ListenAddr instead.

type Options

type Options struct {
	// User is the username to user when connecting.
	User string
	// Hostname is the SSH server's hostname.
	Hostname string

	// KeyFile is an optional path to an unencrypted SSH private key.
	KeyFile string
	// KeyDir is an optional path to a directory (typically $HOME/.ssh) containing standard
	// SSH keys (id_dsa, id_rsa, etc.) to use if authentication via KeyFile is not accepted.
	// Only unencrypted keys are used.
	KeyDir string

	// ConnectTimeout contains a timeout for establishing the TCP connection.
	ConnectTimeout time.Duration
	// ConnectRetries contains the number of times to retry after a connection failure.
	// Each attempt waits up to ConnectTimeout.
	ConnectRetries int
	// ConnectRetryInterval contains the minimum amount of time between connection attempts.
	// This can be set to avoid quickly burning through all retries if errors are returned
	// immediately (e.g. connection refused while the SSH daemon is restarting).
	// The time spent trying to connect counts against this interval.
	ConnectRetryInterval time.Duration

	// WarnFunc (if non-nil) is used to log non-fatal errors encountered while connecting to the host.
	WarnFunc func(string)

	// Platform describes the operating system running on the SSH server. This controls how certain
	// commands will be executed on the remote system. If nil, assumes a Chrome OS system.
	Platform *Platform
}

Options contains options used when connecting to an SSH server.

type Platform

type Platform struct {
	// BuildShellCommand builds the shell command required to execute the given command
	// in the given directory on the target platform. args[0] is the name of the command
	// to be executed. If dir is empty (""), use the default working directory.
	BuildShellCommand func(dir string, args []string) string
}

Platform defines platform-specific behaviours for SSH connections.

type RunOption

type RunOption int

RunOption is the type for options which can be passed to Run, Output, CombinedOutput and Wait to control precise behavior of them.

const DumpLogOnError RunOption = iota

DumpLogOnError instructs to dump logs if the executed command fails (i.e., exited with non-zero status code).

Directories

Path Synopsis
Package linuxssh provides Linux specific operations conducted via SSH TODO(oka): now that this file is not used from framework, simplify the code.
Package linuxssh provides Linux specific operations conducted via SSH TODO(oka): now that this file is not used from framework, simplify the code.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL