sshutils

package
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2024 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultSSHPort    = 22
	DefaultRetryCount = 5
	DefaultRetryDelay = 10 * time.Second
)

Variables

View Source
var (
	TimeInBetweenSSHRetries = 2 * time.Second
	SSHTimeOut              = 1 * time.Minute
	SSHRetryAttempts        = 5
	SSHRetryDelay           = 10 * time.Second
)
View Source
var MockSSHKeyReader = func(path string) ([]byte, error) {

	isPublicKey := len(path) > 4 && path[len(path)-4:] == ".pub"

	if isPublicKey {
		return []byte(testdata.TestPublicSSHKeyMaterial), nil
	} else {
		return []byte(testdata.TestPrivateSSHKeyMaterial), nil
	}
}
View Source
var NewSSHConfigFunc = NewSSHConfig
View Source
var NullCallback = func(int64, int64) {}
View Source
var SSHDialerFunc = NewSSHDial
View Source
var SSHKeyReader = func(path string) ([]byte, error) {
	return os.ReadFile(path)
}

Functions

func ExtractSSHKeyPaths

func ExtractSSHKeyPaths() (string, string, string, string, error)

func GetAggregateSSHTimeout

func GetAggregateSSHTimeout() time.Duration

func GetHostKeyCallback

func GetHostKeyCallback(host string) (ssh.HostKeyCallback, error)

func GetTypedMockClient

func GetTypedMockClient(t *testing.T, log *logger.Logger) (*MockSSHClient, SSHConfiger)

func NewMockSSHClient

func NewMockSSHClient(dialer SSHDialer) (*MockSSHClient, SSHConfiger)

func ReadPrivateKey

func ReadPrivateKey(path string) ([]byte, error)

func ReadPublicKey

func ReadPublicKey(path string) ([]byte, error)

func ValidateSSHKeysFromPath

func ValidateSSHKeysFromPath(publicKeyPath, privateKeyPath string) error

GetSSHKeysFromPath reads and returns the public and private SSH keys from the specified path. If the path ends with ".pub", it is assumed to be the public key, and the corresponding private key is expected to be located at the same path without the ".pub" extension. The function uses SSHKeyReader to read the keys from the filesystem.

Parameters: - path: The filesystem path to the public key or the base path for both keys if the path does not end with ".pub".

Returns: - The public key as the first return value. - The private key as the second return value. - An error if either key could not be read, otherwise nil.

Note: The function assumes that the public and private keys are named identically with the only difference being the ".pub" extension for the public key.

func ValidateSSHPublicKey

func ValidateSSHPublicKey(key string) error

ValidateSSHPublicKey checks if the provided SSH public key is valid

Types

type ExecuteCommandExpectation

type ExecuteCommandExpectation struct {
	Cmd              string
	CmdMatcher       func(string) bool
	ProgressCallback interface{}
	Output           interface{}
	Error            error
	Times            int
}

type Expectation

type Expectation struct {
	Error error
	Times int
}

type ExpectedSSHBehavior

type ExpectedSSHBehavior struct {
	PushFileExpectations             []PushFileExpectation
	ExecuteCommandExpectations       []ExecuteCommandExpectation
	InstallSystemdServiceExpectation *Expectation
	RestartServiceExpectation        *Expectation
}

ExpectedSSHBehavior holds the expected outcomes for SSH methods

type MockSSHClient

type MockSSHClient struct {
	mock.Mock
	Session SSHSessioner
	Dialer  SSHDialer
}

func (*MockSSHClient) Close

func (m *MockSSHClient) Close() error

func (*MockSSHClient) NewSession

func (m *MockSSHClient) NewSession() (SSHSessioner, error)

func (*MockSSHClient) PushFile

func (m *MockSSHClient) PushFile(
	ctx context.Context,
	remotePath string,
	content []byte,
	executable bool,
) error

type MockSSHConfig

type MockSSHConfig struct {
	mock.Mock
	// contains filtered or unexported fields
}

MockSSHConfig is a mock implementation of SSHConfiger

func NewMockSSHConfigWithBehavior

func NewMockSSHConfigWithBehavior(behavior ExpectedSSHBehavior) *MockSSHConfig

NewMockSSHConfigWithBehavior creates a mock SSHConfig based on the expected behavior

func (*MockSSHConfig) Close

func (m *MockSSHConfig) Close() error

func (*MockSSHConfig) Connect

func (m *MockSSHConfig) Connect() (SSHClienter, error)

func (*MockSSHConfig) ExecuteCommand

func (m *MockSSHConfig) ExecuteCommand(
	ctx context.Context,
	cmd string,
) (string, error)

func (*MockSSHConfig) ExecuteCommandWithCallback

func (m *MockSSHConfig) ExecuteCommandWithCallback(
	ctx context.Context,
	cmd string,
	progressCallback func(string),
) (string, error)

func (*MockSSHConfig) GetLastOutput

func (m *MockSSHConfig) GetLastOutput() string

func (*MockSSHConfig) InstallSystemdService

func (m *MockSSHConfig) InstallSystemdService(
	ctx context.Context,
	serviceName string,
	serviceContent string,
) error

func (*MockSSHConfig) PushFile

func (m *MockSSHConfig) PushFile(
	ctx context.Context,
	dst string,
	fileContents []byte,
	executable bool,
) error

func (*MockSSHConfig) PushFileWithCallback

func (m *MockSSHConfig) PushFileWithCallback(
	ctx context.Context,
	dst string,
	fileContents []byte,
	executable bool,
	progressCallback func(int64, int64),
) error

func (*MockSSHConfig) RestartService

func (m *MockSSHConfig) RestartService(ctx context.Context, serviceName string) error

func (*MockSSHConfig) SetSSHClient

func (m *MockSSHConfig) SetSSHClient(sshclient SSHClienter)

func (*MockSSHConfig) StartService

func (m *MockSSHConfig) StartService(
	ctx context.Context,
	serviceName string,
) error

func (*MockSSHConfig) WaitForSSH

func (m *MockSSHConfig) WaitForSSH(
	ctx context.Context,
	retries int,
	retryDelay time.Duration,
) error

type MockSSHDialer

type MockSSHDialer struct {
	mock.Mock
}

MockSSHDialer is a mock implementation of SSHDialer

func NewMockSSHDialer

func NewMockSSHDialer() *MockSSHDialer

NewMockSSHDialer returns a MockSSHDialer with a default implementation

func (*MockSSHDialer) Dial

func (m *MockSSHDialer) Dial(network, addr string, config *ssh.ClientConfig) (SSHClienter, error)

Dial is a mock implementation of the Dial method

type MockSSHSession

type MockSSHSession struct {
	mock.Mock
}

func NewMockSSHSession

func NewMockSSHSession() *MockSSHSession

func (*MockSSHSession) Close

func (m *MockSSHSession) Close() error

func (*MockSSHSession) CombinedOutput

func (m *MockSSHSession) CombinedOutput(cmd string) ([]byte, error)

func (*MockSSHSession) Run

func (m *MockSSHSession) Run(cmd string) error

func (*MockSSHSession) Start

func (m *MockSSHSession) Start(cmd string) error

func (*MockSSHSession) StderrPipe

func (m *MockSSHSession) StderrPipe() (io.Reader, error)

func (*MockSSHSession) StdinPipe

func (m *MockSSHSession) StdinPipe() (io.WriteCloser, error)

func (*MockSSHSession) StdoutPipe

func (m *MockSSHSession) StdoutPipe() (io.Reader, error)

func (*MockSSHSession) Wait

func (m *MockSSHSession) Wait() error

type MockSessioner

type MockSessioner interface {
	Run(cmd string) error
	CombinedOutput(cmd string) ([]byte, error)
	StdinPipe() (io.WriteCloser, error)
	Start(cmd string) error
	Close() error
	Wait() error
}

type MockWriteCloser

type MockWriteCloser struct {
	mock.Mock
}

func (*MockWriteCloser) Close

func (m *MockWriteCloser) Close() error

func (*MockWriteCloser) Write

func (m *MockWriteCloser) Write(p []byte) (n int, err error)

type PushFileExpectation

type PushFileExpectation struct {
	Dst              string
	FileContents     []byte
	Executable       bool
	ProgressCallback interface{}
	Error            error
	Times            int
}

type SFTPClienter

type SFTPClienter interface {
	Create(path string) (io.WriteCloser, error)
	Open(path string) (io.ReadCloser, error)
	Close() error
}

SFTPClienter interface defines the methods we need for SFTP operations

type SFTPDialFunc

type SFTPDialFunc func(conn *ssh.Client) (SFTPClienter, error)

SFTPDial is a function type for creating SFTP clients

type SSHClient

type SSHClient struct {
	SSHClientConfig *ssh.ClientConfig
	Client          SSHClienter
	Dialer          SSHDialer
}

SSHClient struct definition

func (*SSHClient) Close

func (cl *SSHClient) Close() error

func (*SSHClient) NewSession

func (cl *SSHClient) NewSession() (SSHSessioner, error)

type SSHClientWrapper

type SSHClientWrapper struct {
	*ssh.Client
}

func (*SSHClientWrapper) Close

func (w *SSHClientWrapper) Close() error

func (*SSHClientWrapper) NewSession

func (w *SSHClientWrapper) NewSession() (SSHSessioner, error)

type SSHClienter

type SSHClienter interface {
	NewSession() (SSHSessioner, error)
	Close() error
}

SSHClienter interface defines the methods we need for SSH operations

type SSHConfig

type SSHConfig struct {
	Host               string
	Port               int
	User               string
	SSHPrivateKeyPath  string
	PrivateKeyMaterial []byte
	Timeout            time.Duration
	Logger             *logger.Logger

	SSHClient SSHClienter
	SSHDial   SSHDialer

	SSHPrivateKeyReader   func(path string) ([]byte, error)
	SSHPublicKeyReader    func(path string) ([]byte, error)
	ClientConfig          *ssh.ClientConfig
	InsecureIgnoreHostKey bool
}

func (*SSHConfig) Connect

func (c *SSHConfig) Connect() (SSHClienter, error)

func (*SSHConfig) ExecuteCommand

func (c *SSHConfig) ExecuteCommand(ctx context.Context, command string) (string, error)

func (*SSHConfig) ExecuteCommandWithCallback

func (c *SSHConfig) ExecuteCommandWithCallback(ctx context.Context,
	command string,
	callback func(string)) (string, error)

ExecuteCommandWithCallback runs a command on the remote server over SSH. It takes the command as a string argument. It retries the execution a configurable number of times if it fails. It returns the output of the command as a string and any error encountered.

func (*SSHConfig) InstallSystemdService

func (c *SSHConfig) InstallSystemdService(
	ctx context.Context,
	serviceName,
	serviceContent string,
) error

func (*SSHConfig) NewSession

func (c *SSHConfig) NewSession() (SSHSessioner, error)

func (*SSHConfig) PushFile

func (c *SSHConfig) PushFile(
	ctx context.Context,
	remotePath string,
	content []byte,
	executable bool,
) error

func (*SSHConfig) PushFileWithCallback

func (c *SSHConfig) PushFileWithCallback(
	ctx context.Context,
	remotePath string,
	content []byte,
	executable bool,
	_ func(int64, int64),
) error

PushFile copies a local file to the remote server. It takes the local file path and the remote file path as arguments. The file is copied over an SSH session using the stdin pipe. It returns an error if any step of the process fails.

func (*SSHConfig) RestartService

func (c *SSHConfig) RestartService(ctx context.Context, serviceName string) error

func (*SSHConfig) SetSSHClient

func (c *SSHConfig) SetSSHClient(client SSHClienter)

func (*SSHConfig) StartService

func (c *SSHConfig) StartService(ctx context.Context, serviceName string) error

func (*SSHConfig) WaitForSSH

func (c *SSHConfig) WaitForSSH(ctx context.Context, retry int, timeout time.Duration) error

type SSHConfiger

type SSHConfiger interface {
	SetSSHClient(client SSHClienter)
	Connect() (SSHClienter, error)
	WaitForSSH(ctx context.Context, retry int, timeout time.Duration) error
	ExecuteCommand(ctx context.Context, command string) (string, error)
	ExecuteCommandWithCallback(ctx context.Context,
		command string,
		callback func(string)) (string, error)
	PushFile(ctx context.Context, remotePath string, content []byte, executable bool) error
	PushFileWithCallback(ctx context.Context,
		remotePath string,
		content []byte,
		executable bool,
		callback func(int64, int64)) error
	InstallSystemdService(ctx context.Context, serviceName, serviceContent string) error
	StartService(ctx context.Context, serviceName string) error
	RestartService(ctx context.Context, serviceName string) error
}

func NewSSHConfig

func NewSSHConfig(
	host string,
	port int,
	user string,
	sshPrivateKeyPath string,
) (SSHConfiger, error)

type SSHDial

type SSHDial struct {
	DialCreator func(network, addr string, config *ssh.ClientConfig) (SSHClienter, error)
}

func (*SSHDial) Dial

func (d *SSHDial) Dial(network, addr string, config *ssh.ClientConfig) (SSHClienter, error)

type SSHDialer

type SSHDialer interface {
	Dial(network, addr string, config *ssh.ClientConfig) (SSHClienter, error)
}

func NewSSHDial

func NewSSHDial(host string, port int, config *ssh.ClientConfig) SSHDialer

type SSHSessionWrapper

type SSHSessionWrapper struct {
	Session *ssh.Session
}

func (*SSHSessionWrapper) Close

func (s *SSHSessionWrapper) Close() error

func (*SSHSessionWrapper) CombinedOutput

func (s *SSHSessionWrapper) CombinedOutput(cmd string) ([]byte, error)

func (*SSHSessionWrapper) Run

func (s *SSHSessionWrapper) Run(cmd string) error

func (*SSHSessionWrapper) Signal

func (s *SSHSessionWrapper) Signal(sig ssh.Signal) error

func (*SSHSessionWrapper) Start

func (s *SSHSessionWrapper) Start(cmd string) error

func (*SSHSessionWrapper) StderrPipe

func (s *SSHSessionWrapper) StderrPipe() (io.Reader, error)

func (*SSHSessionWrapper) StdinPipe

func (s *SSHSessionWrapper) StdinPipe() (io.WriteCloser, error)

func (*SSHSessionWrapper) StdoutPipe

func (s *SSHSessionWrapper) StdoutPipe() (io.Reader, error)

func (*SSHSessionWrapper) Wait

func (s *SSHSessionWrapper) Wait() error

type SSHSessioner

type SSHSessioner interface {
	Run(cmd string) error
	Start(cmd string) error
	Wait() error
	Close() error
	StdinPipe() (io.WriteCloser, error)
	StdoutPipe() (io.Reader, error)
	StderrPipe() (io.Reader, error)
	CombinedOutput(cmd string) ([]byte, error)
}

Jump to

Keyboard shortcuts

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