sshutils

package
v0.0.22 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2024 License: Apache-2.0 Imports: 24 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        = 3
	SSHDialTimeout          = 3 * time.Second
	SSHClientConfigTimeout  = 3 * time.Second
	SSHRetryDelay           = 3 * 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 ExportRsaPrivateKeyAsPemStr added in v0.0.9

func ExportRsaPrivateKeyAsPemStr(privkey *rsa.PrivateKey) string

func ExportRsaPublicKeyAsPemStr added in v0.0.9

func ExportRsaPublicKeyAsPemStr(pubkey *rsa.PublicKey) (string, error)

func ExtractSSHKeyPaths

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

func GenerateRsaKeyPair added in v0.0.9

func GenerateRsaKeyPair() (*rsa.PrivateKey, *rsa.PublicKey)

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 ParseRsaPrivateKeyFromPemStr added in v0.0.9

func ParseRsaPrivateKeyFromPemStr(privPEM string) (*rsa.PrivateKey, error)

func ParseRsaPublicKeyFromPemStr added in v0.0.9

func ParseRsaPublicKeyFromPemStr(pubPEM string) (*rsa.PublicKey, error)

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 MockSFTPClient added in v0.0.20

type MockSFTPClient struct {
	mock.Mock
}

MockSSHClient is a mock implementation of SSHClienter

func NewMockSFTPClient added in v0.0.20

func NewMockSFTPClient() *MockSFTPClient

type MockSSHClient

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

func (*MockSSHClient) Close

func (m *MockSSHClient) Close() error

func (*MockSSHClient) GetClient added in v0.0.20

func (m *MockSSHClient) GetClient() *ssh.Client

func (*MockSSHClient) IsConnected added in v0.0.18

func (m *MockSSHClient) IsConnected() bool

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) GetHost added in v0.0.20

func (m *MockSSHConfig) GetHost() string

func (*MockSSHConfig) GetLastOutput

func (m *MockSSHConfig) GetLastOutput() string

func (*MockSSHConfig) GetPort added in v0.0.20

func (m *MockSSHConfig) GetPort() int

func (*MockSSHConfig) GetPrivateKeyMaterial added in v0.0.20

func (m *MockSSHConfig) GetPrivateKeyMaterial() []byte

func (*MockSSHConfig) GetSSHClient added in v0.0.20

func (m *MockSSHConfig) GetSSHClient() *ssh.Client

func (*MockSSHConfig) GetSSHClienter added in v0.0.20

func (m *MockSSHConfig) GetSSHClienter() SSHClienter

func (*MockSSHConfig) GetSSHDial added in v0.0.20

func (m *MockSSHConfig) GetSSHDial() SSHDialer

func (*MockSSHConfig) GetUser added in v0.0.20

func (m *MockSSHConfig) GetUser() 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(client *ssh.Client)

func (*MockSSHConfig) SetSSHClienter added in v0.0.20

func (m *MockSSHConfig) SetSSHClienter(clienter SSHClienter)

func (*MockSSHConfig) SetSSHDial added in v0.0.20

func (m *MockSSHConfig) SetSSHDial(dialer SSHDialer)

func (*MockSSHConfig) SetValidateSSHConnection added in v0.0.20

func (m *MockSSHConfig) SetValidateSSHConnection(callback func() error)

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

func (*MockSSHDialer) DialContext added in v0.0.20

func (m *MockSSHDialer) DialContext(
	ctx context.Context,
	network, addr string,
	config *ssh.ClientConfig,
) (SSHClienter, error)

DialContext is a mock implementation of the DialContext 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 SFTPClient added in v0.0.20

type SFTPClient interface {
	MkdirAll(path string) error
	Create(path string) (SFTPFile, error)
	Chmod(path string, mode os.FileMode) error
	Close() error
}

SFTPClient interface defines the SFTP operations we need

type SFTPClientCreator added in v0.0.20

type SFTPClientCreator func(client *ssh.Client) (SFTPClient, error)

SFTPClientCreator is a function type for creating SFTP clients

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 SFTPFile added in v0.0.20

type SFTPFile interface {
	io.WriteCloser
}

SFTPFile interface defines the file operations we need

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) GetClient added in v0.0.20

func (cl *SSHClient) GetClient() *ssh.Client

func (*SSHClient) IsConnected added in v0.0.18

func (cl *SSHClient) IsConnected() bool

func (*SSHClient) NewSession

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

type SSHClientWrapper

type SSHClientWrapper struct {
	*ssh.Client
}

SSHClientWrapper is a thin wrapper around an *ssh.Client that allows us to satisfy the SSHClienter interface.

func (*SSHClientWrapper) Close

func (w *SSHClientWrapper) Close() error

func (*SSHClientWrapper) GetClient added in v0.0.20

func (w *SSHClientWrapper) GetClient() *ssh.Client

func (*SSHClientWrapper) IsConnected added in v0.0.18

func (w *SSHClientWrapper) IsConnected() bool

func (*SSHClientWrapper) NewSession

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

type SSHClienter

type SSHClienter interface {
	NewSession() (SSHSessioner, error)
	IsConnected() bool
	Close() error
	GetClient() *ssh.Client
}

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

	ValidateSSHConnectionFunc func() error
}

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) GetHost added in v0.0.20

func (c *SSHConfig) GetHost() string

func (*SSHConfig) GetPort added in v0.0.20

func (c *SSHConfig) GetPort() int

func (*SSHConfig) GetPrivateKeyMaterial added in v0.0.20

func (c *SSHConfig) GetPrivateKeyMaterial() []byte

func (*SSHConfig) GetSSHClient added in v0.0.20

func (c *SSHConfig) GetSSHClient() *ssh.Client

func (*SSHConfig) GetSSHClienter added in v0.0.20

func (c *SSHConfig) GetSSHClienter() SSHClienter

func (*SSHConfig) GetSSHDial added in v0.0.20

func (c *SSHConfig) GetSSHDial() SSHDialer

func (*SSHConfig) GetUser added in v0.0.20

func (c *SSHConfig) GetUser() string

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

func (*SSHConfig) RestartService

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

func (*SSHConfig) SetSSHClient

func (c *SSHConfig) SetSSHClient(client *ssh.Client)

func (*SSHConfig) SetSSHClienter added in v0.0.20

func (c *SSHConfig) SetSSHClienter(client SSHClienter)

func (*SSHConfig) SetSSHDial added in v0.0.20

func (c *SSHConfig) SetSSHDial(dialer SSHDialer)

func (*SSHConfig) SetValidateSSHConnection added in v0.0.20

func (c *SSHConfig) SetValidateSSHConnection(fn func() error)

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 {
	GetSSHClienter() SSHClienter
	SetSSHClienter(client SSHClienter)
	GetSSHClient() *ssh.Client
	SetSSHClient(client *ssh.Client)

	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

	GetHost() string
	GetPort() int
	GetUser() string
	GetPrivateKeyMaterial() []byte
	GetSSHDial() SSHDialer
	SetSSHDial(dialer SSHDialer)
	SetValidateSSHConnection(func() 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)

func (*SSHDial) DialContext added in v0.0.20

func (d *SSHDial) DialContext(
	ctx context.Context,
	network, addr string,
	config *ssh.ClientConfig,
) (SSHClienter, error)

type SSHDialer

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

func NewSSHDial

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

type SSHError added in v0.0.20

type SSHError struct {
	Cmd    string
	Output string
	Err    error
}

SSHError represents an SSH command execution error with output

func (*SSHError) Error added in v0.0.20

func (e *SSHError) Error() string

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