base

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: May 6, 2022 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultSendOptionsStripPrompt default to stripping prompt.
	DefaultSendOptionsStripPrompt = true
	// DefaultSendOptionsStopOnFailed default to *not* stopping on failures.
	DefaultSendOptionsStopOnFailed = false
	// DefaultSendOptionsTimeoutOps default to relying on the drivers timeout ops attribute.
	DefaultSendOptionsTimeoutOps = -1.0
	// DefaultSendOptionsEager default to *not* eager mode.
	DefaultSendOptionsEager = false
)

Variables

View Source
var ErrCallbackAlreadyTriggered = errors.New("callback set to 'OnlyOnce', but already triggered")
View Source
var ErrCallbackTimeout = errors.New("callback timeout")
View Source
var ErrFailedOpeningTemplate = errors.New("failed opening provided path to textfsm template")

ErrFailedOpeningTemplate error for failure to open a textfsm template.

View Source
var ErrFailedParsingTemplate = errors.New("failed parsing textfsm template")

ErrFailedParsingTemplate error for failure of parsing a textfsm template.

View Source
var ErrIgnoredOption = errors.New("option ignored, for different instance type")
View Source
var ErrMustSetContains = errors.New("must set Contains or ContainsRe")

Functions

func JoinEventInputs

func JoinEventInputs(events []*channel.SendInteractiveEvent) string

JoinEventInputs convenience function to join inputs from a `SendInteractive` method.

func NewChannel

func NewChannel(
	t *transport.Transport,
	options ...Option,
) (*channel.Channel, error)

Types

type Driver

type Driver struct {
	Host string

	AuthUsername             string
	AuthPassword             string
	AuthSecondary            string
	AuthPrivateKey           string
	AuthPrivateKeyPassphrase string
	AuthStrictKey            bool
	AuthBypass               bool

	SSHConfigFile     string
	SSHKnownHostsFile string

	TransportType string
	Transport     *transport.Transport

	Channel *channel.Channel

	FailedWhenContains []string

	PrivilegeLevels    map[string]*PrivilegeLevel
	DefaultDesiredPriv string

	NetconfEcho *bool
}

Driver primary/base driver struct.

func NewDriver

func NewDriver(
	host string,
	options ...Option,
) (*Driver, error)

NewDriver create a new instance of `Driver`, accepts a host and variadic of options to modify the driver behavior.

func (*Driver) Close

func (d *Driver) Close() error

Close closes the connection.

func (*Driver) FormatLogMessage

func (d *Driver) FormatLogMessage(level, msg string) string

FormatLogMessage formats log message payload, adding contextual info about the host.

func (*Driver) FullSendCommand

func (d *Driver) FullSendCommand(
	c string,
	failedWhenContains []string,
	stripPrompt, eager bool,
	timeoutOps time.Duration,
) (*Response, error)

FullSendCommand same as `SendCommand` but requiring explicit options.

func (*Driver) FullSendCommands

func (d *Driver) FullSendCommands(
	c []string,
	failedWhenContains []string,
	stripPrompt, stopOnFailed, eager bool,
	timeoutOps time.Duration,
) (*MultiResponse, error)

FullSendCommands same as `SendCommands` but requiring explicit options.

func (*Driver) FullSendInteractive

func (d *Driver) FullSendInteractive(
	events []*channel.SendInteractiveEvent,
	interactionCompletePatterns,
	failedWhenContains []string,
	timeoutOps time.Duration,
	joinedEventInputs string,
) (*Response, error)

FullSendInteractive same as `SendInteractive` but requiring explicit options.

func (*Driver) GetPrompt

func (d *Driver) GetPrompt() (string, error)

GetPrompt fetch device prompt.

func (*Driver) Open

func (d *Driver) Open() error

Open opens the connection.

func (*Driver) ParseSendOptions

func (d *Driver) ParseSendOptions(
	o []SendOption,
) *SendOptions

ParseSendOptions convenience function to parse and set defaults for `SendOption`s.

func (*Driver) ReadWithCallbacks added in v0.1.2

func (d *Driver) ReadWithCallbacks(
	callbacks []*ReadCallback,
	input string,
	timeout,
	readDelay time.Duration,
) error

func (*Driver) SendCommand

func (d *Driver) SendCommand(c string, o ...SendOption) (*Response, error)

SendCommand send a command to a device, accepts a string command and variadic of `SendOption`s.

func (*Driver) SendCommands

func (d *Driver) SendCommands(
	c []string,
	o ...SendOption,
) (*MultiResponse, error)

SendCommands send commands to a device, accepts a string command and variadic of `SendOption`s.

func (*Driver) SendCommandsFromFile

func (d *Driver) SendCommandsFromFile(
	f string,
	o ...SendOption,
) (*MultiResponse, error)

SendCommandsFromFile send commands from a file to a device, accepts a string command and variadic of `SendOption`s.

func (*Driver) SendInteractive

func (d *Driver) SendInteractive(
	events []*channel.SendInteractiveEvent,
	o ...SendOption,
) (*Response, error)

SendInteractive send interactive commands to a device, accepts a slice of `SendInteractiveEvent` and variadic of `SendOption`s.

type MultiOperationError

type MultiOperationError struct {
	Operations []*OperationError
}

func (*MultiOperationError) Error

func (e *MultiOperationError) Error() string

type MultiResponse

type MultiResponse struct {
	Host        string
	StartTime   time.Time
	EndTime     time.Time
	ElapsedTime float64
	Responses   []*Response
	Failed      error
}

MultiResponse defines a response object for plural operations -- contains a slice of `Responses` for each operation.

func NewMultiResponse

func NewMultiResponse(host string) *MultiResponse

NewMultiResponse creates a new MultiResponse object.

func (*MultiResponse) AppendResponse

func (mr *MultiResponse) AppendResponse(r *Response)

AppendResponse appends a response to the `Responses` attribute of the MultiResponse object.

func (*MultiResponse) JoinedResult

func (mr *MultiResponse) JoinedResult() string

JoinedResult is a convenience method to print out a single unified/joined result -- this is basically all the channel output for each individual response in the MultiResponse joined by newline characters.

type OperationError

type OperationError struct {
	Input       string
	Output      string
	ErrorString string
}

OperationError is an error object returned when a scrapli operation completes "successfully" -- as in does not have an EOF/timeout or otherwise unrecoverable error -- but contains output in the device's response indicating that an input was bad/invalid or device failed to process it at that time.

func (*OperationError) Error

func (e *OperationError) Error() string

Error returns an error string for the OperationError object.

type Option

type Option func(interface{}) error

Option function to set driver options.

func WithAuthBypass

func WithAuthBypass(bypass bool) Option

WithAuthBypass provide bool indicating if auth should be "bypassed" -- only applicable for system and telnet transports.

func WithAuthPassword

func WithAuthPassword(password string) Option

WithAuthPassword provide a string password to use for driver authentication.

func WithAuthPrivateKey

func WithAuthPrivateKey(privateKey string, privateKeyPassphrase ...string) Option

WithAuthPrivateKey provide a string path to a private key to use for driver authentication, optionally provide a string to use for passphrase for given private key.

func WithAuthSecondary

func WithAuthSecondary(secondary string) Option

WithAuthSecondary provide a string "secondary" (or "enable") password to use for driver authentication. Only applicable for "network" level drivers.

func WithAuthStrictKey

func WithAuthStrictKey(stricktKey bool) Option

WithAuthStrictKey provide bool indicating if strict key checking should be enforced.

func WithAuthUsername

func WithAuthUsername(username string) Option

WithAuthUsername provide a string username to use for driver authentication.

func WithChannelAuthPassphrasePattern added in v0.1.3

func WithChannelAuthPassphrasePattern(p *regexp.Regexp) Option

WithChannelAuthPassphrasePattern overrides the default in channel username regexp.

func WithChannelAuthPasswordPattern added in v0.1.3

func WithChannelAuthPasswordPattern(p *regexp.Regexp) Option

WithChannelAuthPasswordPattern overrides the default in channel password regexp.

func WithChannelAuthUsernamePattern added in v0.1.3

func WithChannelAuthUsernamePattern(p *regexp.Regexp) Option

WithChannelAuthUsernamePattern overrides the default in channel username regexp.

func WithChannelLog

func WithChannelLog(log io.Writer) Option

WithChannelLog provide an io.Writer object to write channel log data to.

func WithCommsPromptPattern

func WithCommsPromptPattern(pattern string) Option

WithCommsPromptPattern provide string regex pattern to use for prompt pattern, typically not necessary if using a network level driver.

func WithCommsReturnChar

func WithCommsReturnChar(char string) Option

WithCommsReturnChar provide string to use as the return character, typically can be left default.

func WithDefaultDesiredPriv

func WithDefaultDesiredPriv(defaultDesiredPriv string) Option

WithDefaultDesiredPriv provide custom default preferred privilege level to use -- only applicable to network drivers.

func WithFailedWhenContains

func WithFailedWhenContains(failedWhenContains []string) Option

WithFailedWhenContains provide a custom slice of strings to use to check if an output is failed -- only applicable to network drivers.

func WithNetconfServerEcho

func WithNetconfServerEcho(echo bool) Option

WithNetconfServerEcho provide custom default preferred privilege level to use -- only applicable for netconf.

func WithPort

func WithPort(port int) Option

WithPort modifies the default (22) port value of a driver/transport.

func WithPrivilegeLevels

func WithPrivilegeLevels(privilegeLevels map[string]*PrivilegeLevel) Option

WithPrivilegeLevels provide custom privilege levels to use -- only applicable to network drivers.

func WithSSHConfigFile

func WithSSHConfigFile(sshConfigFile string) Option

WithSSHConfigFile provide string path to ssh config file.

func WithSSHKnownHostsFile

func WithSSHKnownHostsFile(sshKnownHostsFile string) Option

WithSSHKnownHostsFile provide string path to ssh known hosts file.

func WithTimeoutOps

func WithTimeoutOps(timeout time.Duration) Option

WithTimeoutOps provide duration to use for "operation" timeout.

func WithTimeoutSocket

func WithTimeoutSocket(timeout time.Duration) Option

WithTimeoutSocket provide duration to use for socket timeout.

func WithTimeoutTransport

func WithTimeoutTransport(timeout time.Duration) Option

WithTimeoutTransport provide duration to use for transport timeout.

func WithTransportPtySize

func WithTransportPtySize(w, h int) Option

WithTransportPtySize provide pty width/height to use.

func WithTransportType

func WithTransportType(transportType string) Option

WithTransportType provide string name of type of transport to use.

type PrivilegeLevel

type PrivilegeLevel struct {
	Pattern            string
	PatternRe          *regexp.Regexp
	PatternNotContains []string
	Name               string
	PreviousPriv       string
	Deescalate         string
	Escalate           string
	EscalateAuth       bool
	EscalatePrompt     string
}

PrivilegeLevel struct defining a single privilege level -- used only for "network" level drivers.

type ReadCallback added in v0.1.2

type ReadCallback struct {
	Callback func(*Driver, string) error
	Contains string

	NotContains string

	ContainsRe string

	CaseInsensitive bool
	MultiLine       bool
	// ResetOutput bool indicating if the output should be reset or not after callback execution.
	ResetOutput bool
	// OnlyOnce bool indicating if this callback should be executed only one time.
	OnlyOnce bool
	// NextTimout timeout value to use for the subsequent read loop - ignored if Complete is true.
	NextTimeout time.Duration
	// NextReadDelay is time to use for sleeps between reads for hte subsequent read loop.
	NextReadDelay time.Duration

	Complete bool
	Name     string
	// contains filtered or unexported fields
}

func NewReadCallback added in v0.1.2

func NewReadCallback(
	callback func(*Driver, string) error,
	options ...ReadCallbackOption,
) (*ReadCallback, error)

type ReadCallbackOption added in v0.1.2

type ReadCallbackOption func(callback *ReadCallback) error

func WithCallbackCaseInsensitive added in v0.1.2

func WithCallbackCaseInsensitive(i bool) ReadCallbackOption

func WithCallbackComplete added in v0.1.2

func WithCallbackComplete(complete bool) ReadCallbackOption

func WithCallbackContains added in v0.1.2

func WithCallbackContains(contains string) ReadCallbackOption

func WithCallbackContainsRe added in v0.1.2

func WithCallbackContainsRe(contains string) ReadCallbackOption

func WithCallbackMultiline added in v0.1.2

func WithCallbackMultiline(m bool) ReadCallbackOption

func WithCallbackName added in v0.1.2

func WithCallbackName(name string) ReadCallbackOption

func WithCallbackNextReadDelay added in v0.1.2

func WithCallbackNextReadDelay(t time.Duration) ReadCallbackOption

func WithCallbackNextTimeout added in v0.1.2

func WithCallbackNextTimeout(t time.Duration) ReadCallbackOption

func WithCallbackNotContains added in v0.1.2

func WithCallbackNotContains(notContains string) ReadCallbackOption

func WithCallbackOnlyOnce added in v0.1.2

func WithCallbackOnlyOnce(o bool) ReadCallbackOption

func WithCallbackResetOutput added in v0.1.2

func WithCallbackResetOutput(reset bool) ReadCallbackOption

type Response

type Response struct {
	Host               string
	Port               int
	ChannelInput       string
	RawResult          []byte
	Result             string
	StartTime          time.Time
	EndTime            time.Time
	ElapsedTime        float64
	FailedWhenContains []string
	// Failed returns an error if any of the `FailedWhenContains` substrings are seen in the output
	// returned from the device. This error indicates that the operation has completed successfully,
	// but that an input was bad/invalid or device failed to process it at that time
	Failed error
}

Response is a response object that gets returned from scrapli send operations.

func NewResponse

func NewResponse(
	host string,
	port int,
	channelInput string,
	failedWhenContains []string,
) *Response

NewResponse creates a new response object.

func (*Response) FormatLogMessage

func (r *Response) FormatLogMessage(level, msg string) string

FormatLogMessage formats log message payload, adding contextual info about the host.

func (*Response) Record

func (r *Response) Record(rawResult []byte, result string)

Record records a response from an operation.

func (*Response) TextFsmParse

func (r *Response) TextFsmParse(path string) ([]map[string]interface{}, error)

TextFsmParse parses recorded output w/ a provided textfsm template. the argument is interpreted as URL or filesystem path, for example: response.TextFsmParse("http://example.com/textfsm.template") or response.TextFsmParse("./local/textfsm.template").

type SendOption

type SendOption func(*SendOptions)

SendOption func to set send options.

func WithDesiredPrivilegeLevel

func WithDesiredPrivilegeLevel(privilegeLevel string) SendOption

WithDesiredPrivilegeLevel provide a desired privilege level for the send operation to work in.

func WithInteractionCompletePatterns

func WithInteractionCompletePatterns(interactionCompletePatterns []string) SendOption

WithInteractionCompletePatterns provide a list of patterns which, when seen, indicate a `SendInteractive` "session" is complete. Only used for `SendInteractive`, otherwise ignored.

func WithSendEager

func WithSendEager(eager bool) SendOption

WithSendEager bool indicating if send operation should operate in `eager` mode -- generally only used for netconf operations.

func WithSendFailedWhenContains

func WithSendFailedWhenContains(failedWhenContains []string) SendOption

WithSendFailedWhenContains slice of strings that overrides the drivers `FailedWhenContains` list for a given send operation.

func WithSendStopOnFailed

func WithSendStopOnFailed(stopOnFailed bool) SendOption

WithSendStopOnFailed bool indicating if multi command/config operations should stop at first sign of failure (based on FailedWhenContains list).

func WithSendStripPrompt

func WithSendStripPrompt(stripPrompt bool) SendOption

WithSendStripPrompt bool indicating if you would like the hostname/device prompt stripped out of output from a send operation.

func WithSendTimeoutOps

func WithSendTimeoutOps(timeoutOps time.Duration) SendOption

WithSendTimeoutOps duration to use for timeout of a given send operation.

type SendOptions

type SendOptions struct {
	StripPrompt                 bool
	FailedWhenContains          []string
	StopOnFailed                bool
	TimeoutOps                  time.Duration
	Eager                       bool
	DesiredPrivilegeLevel       string
	InteractionCompletePatterns []string
}

SendOptions struct for send operation options.

Jump to

Keyboard shortcuts

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