sshutil

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2022 License: MIT Imports: 16 Imported by: 1

README

sshutil

GoDoc

sshutil provides additional SSH functionality and helper code for working with 'github.com/pkg/sftp' and 'golang.org/x/crypto/ssh'.

Documentation

Overview

Package sshutil provides additional SSH functionality and helper code for working with 'github.com/pkg/sftp' and 'golang.org/x/crypto/ssh'.

Index

Constants

View Source
const (
	ErrorCommandDidNotProduceOutput = "the executed command did not produce any output"
	ErrorNoKnownHostsFilePresent    = "the known hosts file does not exist"
	ErrorUnknownHostKey             = "the specified host is not present in the known hosts file"
	ErrorUploadTimeoutReached       = "upload timeout was exceeded"
	ErrorUploadCanceled             = "the upload was canceled"
)
View Source
const (
	DefaultKnownHostsFileMode = 0600
)
View Source
const (
	OpenSSHPrivateKeyPEMLabel = "OPENSSH PRIVATE KEY"
)

Variables

This section is empty.

Functions

func AddHostKeyToKnownHosts

func AddHostKeyToKnownHosts(knownHostsFilePath string, hostname string, key ssh.PublicKey) error

AddHostKeyToKnownHosts adds a host key to the known hosts file.

func AllowAndAddHostKeyCallBack

func AllowAndAddHostKeyCallBack(hostname string, remote net.Addr, currentKey ssh.PublicKey) error

AllowAndAddHostKeyCallBack permits any host and adds its public key to the known hosts file.

func CurrentUserOpenSSHPrivateKeys added in v0.1.0

func CurrentUserOpenSSHPrivateKeys() ([]ssh.Signer, error)

CurrentUserOpenSSHPrivateKeys returns the current user's OpenSSH private keys. This function implements the input for the ssh.PublicKeysCallback wrapper function. The function itself wraps the FindSSHPrivateKeys function using the default configuration values.

Refer to FindSSHPrivateKeys for more information.

func CurrentUserUnencryptedOpenSSHPrivateKeys added in v0.1.0

func CurrentUserUnencryptedOpenSSHPrivateKeys() ([]ssh.Signer, error)

CurrentUserUnencryptedOpenSSHPrivateKeys returns only the current user's unencrypted OpenSSH private keys. This function implements the input for the ssh.PublicKeysCallback wrapper function.

Refer to FindSSHPrivateKeys for more information.

func FindSSHPrivateKeys added in v0.1.0

func FindSSHPrivateKeys(config FindSSHPrivateKeysConfig) ([]ssh.Signer, error)

FindSSHPrivateKeys searches for SSH private keys, parses them, and returns the corresponding []ssh.Signer using the specified config.

By default the function returns a non-nil error and a zero slice of ssh.Signer if any of the keys cannot be parsed.

func GetKnownHostsFile

func GetKnownHostsFile() (exists bool, filePath string, err error)

GetKnownHostsFile gets the path to the SSH known hosts file. The file path is not returned if the path could not be constructed. An error is returned when the file's path cannot be determined or if the file's mask is not equal to DefaultKnownHostsFileMode.

func ImitateSSHClientHostKeyCallBack

func ImitateSSHClientHostKeyCallBack(promptFunc func(SSHHostKeyPromptInfo) bool) ssh.HostKeyCallback

ImitateSSHClientHostKeyCallBack returns a ssh.HostKeyCallback that imitates the standard SSH command line client's behavior of prompting the user to verify an unknown public key, as well as rejecting mismatched public keys. This callback will call the provided promptFunc, which provides data about the host. The function should return 'true' if the user accepts the SSH host key. The function should return 'false' if the user does not accept the key.

func IsPathSSHPrivateKey added in v0.1.0

func IsPathSSHPrivateKey(config SSHPrivateKeyConfig) (ssh.Signer, bool, error)

IsPathSSHPrivateKey returns a non-nil ssh.Signer, true, and a nil error if the specified file is an SSH private key.

If the file is not an SSH private key, nil ssh.Signer, false, and a nil error are returned. If the file is an SSH private key, but could not be parsed, then nil ssh.Signer, false, and a non-nil error of type *IsSSHPrivateKeyError is returned.

func IsSSHHostKnown

func IsSSHHostKnown(hostPublicKey ssh.PublicKey, targetAddr string, fileContents []byte) (bool, error)

IsSSHHostKnown determines if an SSH server is known by the client according to the specified known hosts file contents.

The targetAddr string can be specified in the following formats:

<hostname>
<hostname>:<port>

The reason targetAddr is a string is because that is what the Go SSH library returns to callback functions.

func OnlyAllowKnownHostsKeyCallBack

func OnlyAllowKnownHostsKeyCallBack(hostname string, remote net.Addr, currentKey ssh.PublicKey) error

OnlyKnownHostKeyCallBack only permits known hosts when connecting to a SSH server. ErrorUnknownHostKey is returned if the host key does not exist in the known hosts file.

func ParseSSHPrivateKey added in v0.2.0

func ParseSSHPrivateKey(config SSHPrivateKeyConfig) (ssh.Signer, error)

ParseSSHPrivateKey wraps IsPathSSHPrivateKey. It requires that the specified file be a SSH private key.

func ParseSSHPrivateKeyFromConfigDirSlice added in v0.2.0

func ParseSSHPrivateKeyFromConfigDirSlice(config SSHPrivateKeyConfig) ([]ssh.Signer, error)

ParseSSHPrivateKeyFromConfigDirSlice looks up the current user's SSH directory and prepends it to the specified file path. In effect, it searches the current user's SSH directory for a private key with the specified file name. It returns a slice of ssh.Signer containing only one key. This is meant to make usage with ssh.PublicKeysCallback more straightforward.

func ParseSSHPrivateKeyIntoSlice added in v0.2.0

func ParseSSHPrivateKeyIntoSlice(config SSHPrivateKeyConfig) ([]ssh.Signer, error)

ParseSSHPrivateKeyIntoSlice wraps ParseSSHPrivateKey, returning a slice of ssh.Signer containing only one key. This is meant to make usage with ssh.PublicKeysCallback more straightforward.

func UploadFileUsingScp

func UploadFileUsingScp(localFilePath string, destinationFilePath string, sshClient *ssh.Client, options UploadOptions) error

UploadFileUsingScp uploads a file using SCP (Secure Copy Protocol). The resulting file name is determined by the value of the destination file path. I.e., specifying a destination of '/root/my-cool-file.txt' results in the file being named 'my-cool-file.txt' located in '/root'. Be aware that the '~' character is not supported. If a timeout occurs, then ErrorUploadTimeoutReached is returned.

func UploadFileUsingSftp

func UploadFileUsingSftp(localFilePath string, destinationFilePath string, sshClient *ssh.Client, options UploadOptions) error

UploadFileUsingSftp uploads a file using SFTP (SSH File Transfer Protocol). The resulting file name is determined by the value of the destination file path. I.e., specifying a destination of '/root/my-cool-file.txt' results in the file being named 'my-cool-file.txt' located in '/root'. Be aware that the '~' character is not supported. If a timeout occurs, then ErrorUploadTimeoutReached is returned.

Types

type CommandOptions

type CommandOptions struct {
	RequireOutput bool
	StripNewLine  bool
}

type CommandResult

type CommandResult struct {
	Output string
	Error  string
}

func ExecuteCommand

func ExecuteCommand(command string, sshClient *ssh.Client, options CommandOptions) CommandResult

ExecuteCommand executes a command on a remote machine using SSH.

func (CommandResult) FirstString

func (o CommandResult) FirstString(delimiter string) string

func (CommandResult) IsError

func (o CommandResult) IsError() bool

func (CommandResult) IsOutputEmpty

func (o CommandResult) IsOutputEmpty() bool

func (CommandResult) LastString

func (o CommandResult) LastString(delimiter string) string

type FindSSHPrivateKeysConfig added in v0.1.0

type FindSSHPrivateKeysConfig struct {
	// DirPathFn must be non-nil, and must return the path of
	// the directory to search. If an error is returned,
	// FindSSHPrivateKeys will stop, and return the error.
	DirPathFn func() (string, error)

	// IgnoreKeyErrFn, if specified, will be called if an error
	// occurs when parsing an SSH private key (the error being passed
	// to the function). If the function returns true, the error will
	// be ignored and FindSSHPrivateKeys will continue to the next
	// private key. If it returns false, FindSSHPrivateKeys will
	// stop parsing keys and return the error.
	IgnoreKeyErrFn func(error) bool

	// KeysToPassFn is a map of private key file names
	// (not absolute paths - only the file's name) to corresponding
	// GetPrivateKeyPasswordFunc. It is referenced when an SSH private
	// key could not be parsed due to a ssh.PassphraseMissingError error.
	// The map can be left uninitialized (nil) if desired.
	KeysToPassFn map[string]GetPrivateKeyPasswordFunc
}

FindSSHPrivateKeysConfig configures the FindSSHPrivateKeys function.

func (FindSSHPrivateKeysConfig) Validate added in v0.1.0

func (o FindSSHPrivateKeysConfig) Validate() error

type GetPrivateKeyPasswordFunc added in v0.2.0

type GetPrivateKeyPasswordFunc func() (password string, err error)

GetPrivateKeyPasswordFunc returns a password for the current private key. An error can also be returned if the password could not be retrieved. In such cases, the calling function will honor the failure and return.

type IsSSHPrivateKeyError added in v0.1.0

type IsSSHPrivateKeyError struct {
	FilePath              string
	UnableToOpen          bool
	StatFail              bool
	CurrentFileMode       os.FileMode
	BadFileMode           bool
	CopyContentsFail      bool
	ParseFail             bool
	RequiresPassphrase    bool
	OptionalUnderlyingErr error
	Message               string
}

func (IsSSHPrivateKeyError) Error added in v0.1.0

func (o IsSSHPrivateKeyError) Error() string

type SSHHostKeyPromptInfo

type SSHHostKeyPromptInfo struct {
	UserFacingPrompt    string
	FoundKnownHostsFile bool
	RemoteHostname      string
	RemotePublicKey     ssh.PublicKey
}

type SSHPrivateKeyConfig added in v0.2.0

type SSHPrivateKeyConfig struct {
	// FilePath is the file to attempt to parse. The usage of this field
	// may vary from function to function. Refer to the calling function's
	// documentation for details..
	FilePath string

	// PEMLabel, if specified, is the PEM label to search for.
	//
	// The purpose of this field is to identify if the current file
	// is a PEM-encoded private key without parsing the entire file.
	// If the first line of the file is not equal to the specified label,
	// then the function will return false and a nil error.
	//
	// A PEM label is the portion of the PEM header that contains the
	// expected data type. For example, the PEM label of the header:
	//	-----BEGIN OPENSSH PRIVATE KEY-----
	//
	// ... would be:
	//	OPENSSH PRIVATE KEY
	//
	// Refer to RFC 7468 for more information:
	// https://tools.ietf.org/html/rfc7468
	PEMLabel string

	// PassFn is an optional GetPrivateKeyPasswordFunc. This function
	// is invoked only if it is non-nil and the current file is an SSH
	// private key that requires a passphrase.
	PassFn GetPrivateKeyPasswordFunc
}

SSHPrivateKeyConfig configures an SSH private key parsing function.

type TransferProgress

type TransferProgress struct {
	LocalFileSize  int64
	RemoteFileSize int64
	Percent        int
}

type UploadOptions

type UploadOptions struct {
	Cancel   chan bool
	Progress chan TransferProgress
	Timeout  time.Duration
}

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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