sshclient

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2024 License: BSD-3-Clause Imports: 15 Imported by: 1

README

SSH client

This package manages ssh connections to other hosts ("client" mode), using the Go standard ssh library. It provides a similar interface as the exec package, e.g., with Run, Output, Start functions to execute commands, and its Config is based on exec.Config.

The Client type is used to establish a connection to a host, which persists until closed.

Each command execution process creates its own ssh.Session object that manages the process of running the command, within the scope of a persistently open Client connection. This is much faster than opening a new connection for each command. A map of open sessions is maintained in case of a Start command that runs the command asynchronously.

A good reference for similar package: https://github.com/helloyi/go-sshclient

scp

The https://github.com/bramvdbogaerde/go-scp package is used to implement the scp protocol on top of our client.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	Config

	// ssh client is present (non-nil) after a successful Connect
	Client *ssh.Client

	// keeps track of sessions that are being waited upon
	Sessions map[string]*ssh.Session
	// contains filtered or unexported fields
}

Client represents a persistent connection to an ssh host. Commands are run by creating [ssh.Session]s from this client.

func NewClient

func NewClient(cfg *Config) *Client

NewClient returns a new Client using given Config configuration parameters.

func (*Client) Close

func (cl *Client) Close()

Close terminates any open Sessions and then closes the Client connection.

func (*Client) CloseSessions

func (cl *Client) CloseSessions()

CloseSessions terminates any open Sessions that are still Waiting for the associated process to finish.

func (*Client) Connect

func (cl *Client) Connect(host string) error

Connect connects to given host, which can either be just the host or user@host. If host is empty, the Config default host will be used if non-empty, or an error is returned. If successful, creates a Client that can be used for future sessions. Otherwise, returns error. This updates the Host (and User) fields in the config, for future reference.

func (*Client) CopyHostToLocal

func (cl *Client) CopyHostToLocal(ctx context.Context, hostFilename string, w io.Writer) error

CopyHostToLocal copies given filename on the already-connected remote host, to the local io.Writer using the 'scp' protocol. See ScpPath in Config for path to scp on remote host. If the host filename is not absolute (i.e, doesn't start with /) then the current Dir path on the Client is prepended to the target path. Use context.Background() for a basic context if none otherwise in use.

func (*Client) CopyHostToLocalFile

func (cl *Client) CopyHostToLocalFile(ctx context.Context, hostFilename, localFilename string) error

CopyHostToLocalFile copies given filename on the already-connected remote host, to the local file using the 'scp' protocol. See ScpPath in Config for path to scp on remote host. If the host filename is not absolute (i.e, doesn't start with /) then the current Dir path on the Client is prepended to the target path. Use context.Background() for a basic context if none otherwise in use.

func (*Client) CopyLocalFileToHost

func (cl *Client) CopyLocalFileToHost(ctx context.Context, localFilename, hostFilename string) error

CopyLocalFileToHost copies given local file to given host file on the already-connected remote host, using the 'scp' protocol. See ScpPath in Config for path to scp on remote host. If the host filename is not absolute (i.e, doesn't start with /) then the current Dir path on the Client is prepended to the target path. Use context.Background() for a basic context if none otherwise in use.

func (*Client) CopyLocalToHost

func (cl *Client) CopyLocalToHost(ctx context.Context, r io.Reader, size int64, hostFilename string) error

CopyLocalToHost copies given io.Reader source data to given filename on the already-connected remote host, using the 'scp' protocol. See ScpPath in Config for path to scp on remote host. The size must be given in advance for the scp protocol. If the host filename is not absolute (i.e, doesn't start with /) then the current Dir path on the Client is prepended to the target path. Use context.Background() for a basic context if none otherwise in use.

func (*Client) Exec

func (cl *Client) Exec(sio *exec.StdIOState, start, output bool, cmd string, args ...string) (string, error)

Exec executes the command, piping its stdout and stderr to the config writers. If the command fails, it will return an error with the command output. The given cmd and args may include references to environment variables in $FOO format, in which case these will be expanded before the command is run.

Ran reports if the command ran (rather than was not found or not executable). Code reports the exit code the command returned if it ran. If err == nil, ran is always true and code is always 0.

func (*Client) GetHomeDir

func (cl *Client) GetHomeDir() error

GetHomeDir runs "pwd" on the host to get the users home dir, called right after connecting.

func (*Client) NewSession

func (cl *Client) NewSession(interact bool) (*ssh.Session, error)

NewSession creates a new session, sets its input / outputs based on config. Only works if Client already connected.

func (*Client) Output

func (cl *Client) Output(sio *exec.StdIOState, cmd string, args ...string) (string, error)

Output runs the command and returns the text from stdout.

func (*Client) Run

func (cl *Client) Run(sio *exec.StdIOState, cmd string, args ...string) error

Run runs given command, using config input / outputs. Must have already made a successful Connect.

func (*Client) Start

func (cl *Client) Start(sio *exec.StdIOState, cmd string, args ...string) error

Start starts the given command with arguments.

func (*Client) WaitSession

func (cl *Client) WaitSession(name string, ses *ssh.Session) error

WaitSession adds the session to list of open sessions, and calls Wait on it. It should be called in a goroutine, and will only return when the command is completed or terminated. The given name is used to save the session in a map, for later reference. If left blank, the name will be a number that increases with each such session created.

type Config

type Config struct {
	exec.Config

	// user name and ssh key info
	User User

	// host name / ip address to connect to. can be blank, in which
	// case it must be specified in the Client.Connect call.
	Host string

	// home directory of user on remote host,
	// which is captured at initial connection time.
	HomeDir string

	// ScpPath is the path to the `scp` executable on the host,
	// for copying files between local and remote host.
	// Defaults to /usr/bin/scp
	ScpPath string `default:"/usr/bin/scp"`
}

Config contains the configuration information that controls the behavior of ssh connections and commands. It is used to establish a Client connection to a remote host. It builds on the shared settings in exec.Config

func NewConfig

func NewConfig(cfg *exec.Config) *Config

NewConfig returns a new ssh Config based on given exec.Config parameters.

type User

type User struct {
	// user name to connect with
	User string

	// path to ssh keys: ~/.ssh by default
	KeyPath string

	// name of ssh key file in KeyPath: .pub is appended for public key
	KeyFile string `default:"id_rsa"`
}

User holds user-specific ssh connection configuration settings, including Key info.

func (*User) Defaults

func (us *User) Defaults()

Jump to

Keyboard shortcuts

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