forked from networklore/netrasp
/
ios.go
107 lines (87 loc) · 2.52 KB
/
ios.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package netrasp
import (
"context"
"fmt"
"regexp"
"strings"
)
var generalPrompt = regexp.MustCompile(`(^[a-zA-Z0-9_-]+[#|>])|(^[a-zA-Z0-9_-]+\([a-z-]+\)#)`)
var enablePrompt = regexp.MustCompile(`^[Pp]assword:`)
// Ios is the Netrasp driver for Cisco IOS.
type ios struct {
Connection connection
}
// Close connection to device.
func (i ios) Close(ctx context.Context) error {
i.Connection.Close(ctx)
return nil
}
// Configure device.
func (i ios) Configure(ctx context.Context, commands []string) (ConfigResult, error) {
var result ConfigResult
_, err := i.Run(ctx, "configure terminal")
if err != nil {
return result, fmt.Errorf("unable to enter config mode: %w", err)
}
for _, command := range commands {
output, err := i.Run(ctx, command)
configCommand := ConfigCommand{Command: command, Output: output}
result.ConfigCommands = append(result.ConfigCommands, configCommand)
if err != nil {
return result, fmt.Errorf("unable to run command '%s': %w", command, err)
}
}
_, err = i.Run(ctx, "end")
if err != nil {
return result, fmt.Errorf("unable to exit from config mode: %w", err)
}
return result, nil
}
// Dial opens a connection to a device.
func (i ios) Dial(ctx context.Context) error {
commands := []string{"terminal length 0", "terminal width 511"}
return establishConnection(ctx, i, i.Connection, i.basePrompt(), commands)
}
// Enable elevates privileges.
func (i ios) Enable(ctx context.Context) error {
_, err := i.RunUntil(ctx, "enable", enablePrompt)
if err != nil {
return err
}
host := i.Connection.GetHost()
_, err = i.Run(ctx, host.password)
if err != nil {
return err
}
return nil
}
// Run executes a command on a device.
func (i ios) Run(ctx context.Context, command string) (string, error) {
output, err := i.RunUntil(ctx, command, i.basePrompt())
if err != nil {
return "", err
}
output = strings.ReplaceAll(output, "\r\n", "\n")
lines := strings.Split(output, "\n")
result := ""
for i := 1; i < len(lines)-1; i++ {
result += lines[i] + "\n"
}
return result, nil
}
// RunUntil executes a command and reads until the provided prompt.
func (i ios) RunUntil(ctx context.Context, command string, prompt *regexp.Regexp) (string, error) {
err := i.Connection.Send(ctx, command)
if err != nil {
return "", fmt.Errorf("unable to send command to device: %w", err)
}
reader := i.Connection.Recv(ctx)
output, err := readUntilPrompt(ctx, reader, prompt)
if err != nil {
return "", err
}
return output, nil
}
func (i ios) basePrompt() *regexp.Regexp {
return generalPrompt
}