-
Notifications
You must be signed in to change notification settings - Fork 0
/
abc.go
179 lines (162 loc) · 3.95 KB
/
abc.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package main
import (
"bufio"
"encoding/csv"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"regexp"
"strings"
"sync"
"time"
"golang.org/x/crypto/ssh"
"gopkg.in/yaml.v2"
)
type result struct {
data [][]string
m sync.Mutex
}
type Input struct {
Version string `yaml:"version"`
Credentials struct {
Username string `yaml:"username"`
Password string `yaml:"password"`
}
Commands []struct {
Command string `yaml:"command"`
}
Hosts []struct {
Host string `yaml:"host"`
}
}
func main() {
var wg sync.WaitGroup
var r result
i := parseInput()
for _, target := range i.Hosts {
wg.Add(1)
go worker(i, &r, target.Host, &wg)
}
wg.Wait()
csvFile, err := os.Create("output.csv")
if err != nil {
log.Fatal(err.Error())
}
csvwriter := csv.NewWriter(csvFile)
csvwriter.Write([]string{"Hostname", "Model Number", "Software Version"})
for _, empRow := range r.data {
if err := csvwriter.Write(empRow); err != nil {
log.Fatal(err.Error())
}
}
csvwriter.Flush()
}
func authenticate(host, username, password string) (ssh.Client, error) {
// Create client config
config := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.Password(password),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: time.Second * 5,
}
// Connect to the remote server and perform the SSH handshake.
client, err := ssh.Dial("tcp", host+":22", config)
return *client, err
}
func extractItem(output []string, pattern *regexp.Regexp) string {
template := []byte("$name")
result := []byte{}
var target string
for _, v := range output {
content := []byte(v)
for _, submatches := range pattern.FindAllSubmatchIndex(content, -1) {
result = pattern.Expand(result, template, content, submatches)
}
}
target = string(result)
target = strings.Replace(target, "\n", "", -1)
return target
}
func parseInput() Input {
var i Input
if len(os.Args) < 2 {
log.Fatal("input.yml is not specified. Quitting....")
}
inputFile := os.Args[1]
b, err := ioutil.ReadFile(inputFile)
if err != nil {
log.Fatal("Unable to read file %s. Quitting..." + os.Args[1])
}
if err = yaml.Unmarshal(b, &i); err != nil {
log.Fatal("Unable to parse file" + os.Args[1])
}
return i
}
func worker(input Input, r *result, target string, wg *sync.WaitGroup) {
client, err := authenticate(target, input.Credentials.Username, input.Credentials.Password)
if err != nil {
log.Fatalf("unable to connect: %v", err)
}
defer client.Close()
// Create a session
session, err := client.NewSession()
if err != nil {
log.Fatal("Failed to create session: ", err)
}
defer session.Close()
stdin, err := session.StdinPipe()
if err != nil {
fmt.Println(err.Error())
}
session.Stderr = os.Stderr
reader, err := session.StdoutPipe()
if err != nil {
fmt.Println(err.Error())
}
b := bufio.NewReader(reader)
go func() {
output := []string{}
for {
text, _, err := b.ReadLine()
if err == io.EOF {
break
}
output = append(output, string(text))
}
hostnameRegExp := regexp.MustCompile(`hostname\s+(?P<name>[a-zA-Z0-9._-]+)`)
hostname := extractItem(output, hostnameRegExp)
modelNumberRegExp := regexp.MustCompile(`Model\snumber\s+:\s(?P<name>[a-zA-Z0-9._-]+)`)
modelNumber := extractItem(output, modelNumberRegExp)
//Get the software version of the master switch only
softwareVersionRegExp := regexp.MustCompile(`\*\s+\d\s\d+\s+[a-zA-Z0-9._-]+\s+(?P<name>[^\s]+)\s+[^\s]+`)
softwareVersion := extractItem(output, softwareVersionRegExp)
r.m.Lock()
r.data = append(r.data, []string{hostname, modelNumber, softwareVersion})
r.m.Unlock()
wg.Done()
}()
if err := session.Shell(); err != nil {
log.Fatal(err)
}
stdin.Write([]byte("terminal length 0\n"))
for _, c := range input.Commands {
stdin.Write([]byte(c.Command + "\n"))
}
stdin.Write([]byte("exit\n"))
session.Wait()
}
// //input.yml
// version: 1
// credentials:
// username:
// password:
// commands:
// - command:
// - command:
// hosts:
// - host:
// - host: