-
Notifications
You must be signed in to change notification settings - Fork 50
/
main.go
373 lines (336 loc) · 8.14 KB
/
main.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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package main
import (
"bufio"
"fmt"
"net"
"os"
"os/user"
"path/filepath"
"strings"
"sync"
"github.com/containerd/containerd/pkg/progress"
"github.com/mattn/go-colorable"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
// preload initializes any global options and configuration
// before the main or sub commands are run
func preload(context *cli.Context) error {
if context.GlobalBool("debug") {
log.SetLevel(log.DebugLevel)
}
return nil
}
// loadHosts returns a list of host addresses that are specified on the
// command line and also in a hosts file separated by new lines.
func loadHosts(context *cli.Context) ([]string, error) {
hosts := []string(context.GlobalStringSlice("host"))
if hostsFile := context.GlobalString("hosts"); hostsFile != "" {
f, err := os.Open(hostsFile)
if err != nil {
return nil, err
}
defer f.Close()
s := bufio.NewScanner(f)
for s.Scan() {
hosts = append(hosts, s.Text())
}
if err := s.Err(); err != nil {
return nil, err
}
}
return hosts, nil
}
// multiplexAction uses the arguments passed via the command line and
// multiplexes them across multiple SSH connections
func multiplexAction(context *cli.Context) error {
c, err := newCommand(context)
if err != nil {
return err
}
log.Debug(c)
hosts, err := loadHosts(context)
if err != nil {
return err
}
concurrent := context.GlobalInt("concurrency")
lines := context.GlobalInt("lines")
// Parse OpenSSH client config file at ~/.ssh/config:
user, err := user.Current()
if err != nil {
return err
}
sections, err := ParseSSHConfigFile(filepath.Join(user.HomeDir, ".ssh", "config"))
if err != nil {
return err
}
if len(hosts) == 0 {
return fmt.Errorf("no host specified for command to run")
}
log.Debugf("hosts %v", hosts)
agentForwarding := context.GlobalBool("A")
var agt agent.Agent
if agentForwarding {
agt, err = newAgent()
if err != nil {
return err
}
}
identityFiles := []string{}
if c.Identity != "" {
identityFiles = append(identityFiles, c.Identity)
}
methods := defaultAuthMethods(identityFiles, agt)
plainOptions := []string(context.GlobalStringSlice("option"))
cliOptions := ParseOptions(plainOptions)
quiet := context.GlobalBool("quiet")
wg := &sync.WaitGroup{}
usr := c.User
work := make(chan *job, 64)
// add workers for concurrency level
for i := 0; i < concurrent; i++ {
wg.Add(1)
go executeCommand(wg, work, c, usr, agt, methods, cliOptions, quiet)
}
var jobs []*job
signal := make(chan struct{}, len(jobs))
for _, host := range hosts {
jobs = append(jobs, &job{
host: host,
config: sections[host],
signal: signal,
state: pending,
})
}
w := progress.NewWriter(colorable.NewColorableStdout())
var wwg sync.WaitGroup
wwg.Add(1)
go func() {
defer wwg.Done()
for range signal {
w.Flush()
for _, i := range jobs {
fmt.Fprintf(w, lineformat, formatHostLine(i), i.read(lines))
}
w.Flush()
}
}()
// send work
for _, j := range jobs {
work <- j
}
close(work)
wg.Wait()
close(signal)
wwg.Wait()
log.Debugf("finished executing %s on all hosts", c)
return nil
}
func getState(i int) string {
switch i {
case pending:
return "PENDING"
case running:
return "RUNNING"
case finished:
return "FINISHED"
default:
return "UNKNOWN"
}
}
func formatHostLine(j *job) string {
var (
status = green
statemsg = ""
)
if j.err != nil {
status = red
statemsg = fmt.Sprintf(": ERROR %s", j.err)
} else {
statemsg = fmt.Sprintf(": %s", getState(j.state))
}
return fmt.Sprintf("%s%s%s%s%s",
status,
underline,
j.host,
statemsg,
reset,
)
}
const (
escape = "\x1b"
reset = escape + "[0m"
red = escape + "[31m" // nolint: deadcode, varcheck, unused
green = escape + "[32m"
underline = escape + "[4m"
)
const lineformat = "%s\n%s\n"
const (
pending = iota + 1
running
finished
)
type job struct {
host string
config SSHClientOptions
signal chan struct{}
lines []string
err error
state int
}
func (i *job) read(count int) string {
l := len(i.lines)
from := l - count
if from < 0 {
return strings.Join(i.lines, "\n")
}
return strings.Join(i.lines[from:], "\n")
}
func executeCommand(wg *sync.WaitGroup, jobs chan *job, c command, user string, agt agent.Agent, methods map[string]ssh.AuthMethod, cliOptions SSHClientOptions, quiet bool) {
defer wg.Done()
for job := range jobs {
job.state = running
job.signal <- struct{}{}
var err error
if job.host, err = cleanHost(job.host); err != nil {
job.err = err
continue
}
if err = runSSH(job, c, user, agt, methods, cliOptions, quiet); err != nil {
job.err = err
}
job.state = finished
job.signal <- struct{}{}
}
}
// runSSH executes the given command on the given host.
// All available SSH authentication methods to the host will be tried.
func runSSH(job *job, c command, user string, agt agent.Agent, methods map[string]ssh.AuthMethod, cliOptions SSHClientOptions, quiet bool) error {
options := getEffectiveClientOptions(job.config, cliOptions)
log.Debugf("Using SSH client options: %q", options)
if options.User != "" {
user = options.User
}
if options.HostName != "" {
job.host = net.JoinHostPort(options.HostName, options.Port)
}
if options.IdentityFile != "" {
if m, err := newSSHPublicKeyAuthMethod(options.IdentityFile); err == nil {
methods[options.IdentityFile] = m
}
}
// Try using each available AuthMethod to establish SSH session:
var (
session *sshSession
err error
)
for k, m := range methods {
config := newSSHClientConfig(user, job.host, agt, m)
session, err = config.NewSession(options)
if err == nil {
log.Debugf("Session established using identity file %s", k)
break // Session established, quit trying the next AuthMethod
}
log.Debugf("Failed to establish session using identity file %s - %v", k, err)
}
if session == nil {
return fmt.Errorf("none of the provided authentication methods can establish SSH session successfully")
}
if !quiet {
w := newWriter(job)
session.Stderr, session.Stdout = w, w
}
defer func() {
session.Close()
// log.Printf("Session complete from %s@%s", user, job.host)
}()
for key, value := range c.Env {
if err := session.Setenv(key, value); err != nil {
return err
}
}
return session.Run(c.Cmd)
}
// cleanHost parses out the hostname/ip and port. If no port is
// specified then port 22 is appended to the hostname/ip
func cleanHost(host string) (string, error) {
h, port, err := net.SplitHostPort(host)
if err != nil {
if !strings.Contains(err.Error(), "missing port in address") {
return "", err
}
port = "22"
h = host
}
if port == "" {
port = "22"
}
return net.JoinHostPort(h, port), nil
}
func main() {
app := cli.NewApp()
app.Name = "slex"
app.Usage = "SSH commands multiplexed"
app.Version = "4"
app.Author = "@crosbymichael"
app.Email = "[email protected]"
app.Before = preload
app.Flags = []cli.Flag{
cli.BoolFlag{
Name: "debug",
Usage: "enable debug output for the logs",
},
cli.StringSliceFlag{
Name: "host",
Value: &cli.StringSlice{},
Usage: "SSH host address",
},
cli.StringFlag{
Name: "hosts",
Usage: "file containing host addresses separated by a new line",
},
cli.StringFlag{
Name: "user,u",
Value: "root",
Usage: "user to execute the command as",
},
cli.StringFlag{
Name: "identity,i",
Usage: "SSH identity to use for connecting to the host",
},
cli.StringSliceFlag{
Name: "option,o",
Value: &cli.StringSlice{},
Usage: "SSH client option",
},
cli.BoolFlag{
Name: "agent,A",
Usage: "Forward authentication request to the ssh agent",
},
cli.StringSliceFlag{
Name: "env,e",
Usage: "set environment variables for SSH command",
Value: &cli.StringSlice{},
},
cli.BoolFlag{
Name: "quiet,q",
Usage: "disable output from the ssh command",
},
cli.IntFlag{
Name: "concurrency,c",
Usage: "set the concurrent worker limit",
Value: 10,
},
cli.IntFlag{
Name: "lines,l",
Usage: "number of lines to display on screen at once",
Value: 5,
},
}
app.Action = multiplexAction
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}