/
pssh.go
459 lines (418 loc) · 9.75 KB
/
pssh.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
package pssh
import (
"bytes"
"context"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"path"
"regexp"
"strings"
"sync"
"time"
"github.com/fatih/color"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
)
const (
one = 1
)
type prn interface {
Print(a ...interface{}) (n int, err error)
Printf(format string, a ...interface{}) (n int, err error)
}
type print struct {
colorMode bool
output io.Writer
red prn
boldRed prn
green prn
}
// ToSlice comma separated to slice
func ToSlice(s string) []string {
return strings.Split(s, ",")
}
func newPrint(output io.Writer, colorMode bool) *print {
p := &print{
output: output,
colorMode: colorMode,
}
p.init()
return p
}
func (p *print) init() {
if p.colorMode {
p.red = color.New(color.FgRed)
p.boldRed = color.New(color.FgRed).Add(color.Bold)
p.green = color.New(color.FgGreen)
return
}
p.red = p
p.boldRed = p
p.green = p
}
func (p *print) Print(a ...interface{}) (n int, err error) {
return fmt.Fprint(p.output, a...)
}
func (p *print) Printf(format string, a ...interface{}) (n int, err error) {
return fmt.Fprintf(p.output, format, a...)
}
type sshDialIface interface {
Dial(network, addr string, config *ssh.ClientConfig) (sshClientIface, error)
}
type sshDial struct{}
func (n sshDial) Dial(network, addr string, config *ssh.ClientConfig) (sshClientIface, error) {
return ssh.Dial(network, addr, config)
}
type sshClientIface interface {
ssh.Conn
Dial(n, addr string) (net.Conn, error)
DialTCP(n string, laddr, raddr *net.TCPAddr) (net.Conn, error)
HandleChannelOpen(channelType string) <-chan ssh.NewChannel
Listen(n, addr string) (net.Listener, error)
ListenTCP(laddr *net.TCPAddr) (net.Listener, error)
ListenUnix(socketPath string) (net.Listener, error)
NewSession() (*ssh.Session, error)
}
// Pssh pssh struct
type Pssh struct {
*Config
*print
concurrentGoroutines chan struct{}
stdoutPool sync.Pool
stderrPool sync.Pool
//netDial func(network, address string) (net.Conn, error)
sshDialer sshDialIface
conInstances chan conInstance
cws []*conWork
clientConf ssh.ClientConfig
identFileData [][]byte
conns *connPools
}
// Config pssh config
type Config struct {
Concurrency int
MaxAgentConns int
User string
Hostsfile string
ShowHostName bool
ColorMode bool
IgnoreHostKey bool
Debug bool
StdinFlag bool
IdentityFileOnly bool
SortPrint bool
Timeout time.Duration
KexFlag string
SSHAuthSocket string
IdentFiles []string
// ciphers
Kex []string
Ciphers []string
Macs []string
}
func newBytesBuf() interface{} { return new(bytes.Buffer) }
// Init Pssh
func (p *Pssh) Init() {
p.concurrentGoroutines = make(chan struct{}, p.Concurrency)
p.print = newPrint(os.Stdout, p.ColorMode)
p.stdoutPool = sync.Pool{New: newBytesBuf}
p.stderrPool = sync.Pool{New: newBytesBuf}
p.sshDialer = sshDial{}
p.identFileData = p.readIdentFiles()
}
type input struct {
id int
command string
stdin string
results chan<- *result
}
type result struct {
conID int
sessionID int
code int
err error
stdout *bytes.Buffer
stderr *bytes.Buffer
}
type conInstance struct {
*conWork
err error
}
func (p *Pssh) newResult(conID, sessionID int) *result {
r := &result{
conID: conID,
sessionID: sessionID,
stdout: p.stdoutPool.Get().(*bytes.Buffer),
stderr: p.stderrPool.Get().(*bytes.Buffer),
}
r.stdout.Reset()
r.stderr.Reset()
return r
}
func (p *Pssh) delReslt(r *result) {
p.stdoutPool.Put(r.stdout)
p.stderrPool.Put(r.stderr)
}
// nolint:gochecknoglobals
var re = regexp.MustCompile(":.+")
func readHosts(fileName string) ([]string, error) {
// nolint: gosec
data, err := ioutil.ReadFile(fileName)
if err != nil {
return nil, err
}
lines := bytes.Fields(data)
res := make([]string, len(lines))
for i := range lines {
res[i] = string(lines[i])
if !re.MatchString(res[i]) {
res[i] += ":22"
}
}
return res, nil
}
func getHostKeyCallback(insecure bool) (ssh.HostKeyCallback, error) {
if insecure {
// nolint: gosec
return ssh.InsecureIgnoreHostKey(), nil
}
file := path.Join(os.Getenv("HOME"), ".ssh/known_hosts")
cb, err := knownhosts.New(file)
if err != nil {
return nil, errors.Wrap(err, "knownhosts.New")
}
return cb, nil
}
func (p *Pssh) newConWork(id int, host string) *conWork {
c := &conWork{Pssh: p, id: id, host: host, command: make(chan input, one)}
c.startSession = c.startSessionWorker
return c
}
func (p *Pssh) setConnPool() {
if len(p.SSHAuthSocket) == 0 {
return
}
p.conns = newConnPools(p.SSHAuthSocket, p.MaxAgentConns)
}
// Run main task
func (p *Pssh) Run() int {
hosts, err := readHosts(p.Hostsfile)
if err != nil {
// nolint: errcheck,gosec
log.Printf("read hosts file err: %s", err)
return one
}
hc, err := getHostKeyCallback(p.IgnoreHostKey)
if err != nil {
// nolint: errcheck,gosec
log.Printf("read hosts file err: %s", err)
return one
}
p.setConnPool()
p.clientConf = ssh.ClientConfig{
User: p.User,
//Auth: p.getAuthMethods(),
Timeout: p.Timeout,
HostKeyCallback: hc,
Config: ssh.Config{KeyExchanges: p.Config.Kex, Ciphers: p.Config.Ciphers, MACs: p.Config.Macs},
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
p.conInstances = make(chan conInstance, len(hosts))
p.cws = make([]*conWork, len(hosts))
for i, host := range hosts {
p.cws[i] = p.newConWork(i, host)
}
go p.runConWorkers(ctx)
go func() {
if ierr := p.getConInstanceErrs(); ierr != nil {
log.Print(ierr)
cancel()
}
}()
stdin := []byte{}
if p.StdinFlag {
if stdin, err = ioutil.ReadAll(os.Stdin); err != nil {
log.Fatal(err)
}
}
results := make(chan *result, len(hosts))
in := input{
command: strings.Join(flag.Args(), " "),
stdin: string(stdin),
results: results,
}
for i := range p.cws {
p.cws[i].command <- in
}
code := p.outputFunc()(ctx, results, p.cws)
cancel()
return code
}
func (p *Pssh) runConWorkers(ctx context.Context) int {
for i := range p.cws {
if p.Concurrency > 0 {
p.concurrentGoroutines <- struct{}{}
}
go p.cws[i].conWorker(ctx, p.clientConf, p.conInstances)
}
return len(p.cws)
}
func (p *Pssh) getConInstanceErrs() error {
for con := range p.conInstances {
if con.err != nil {
// nolint: errcheck,gosec
return fmt.Errorf("host:%s err:%s", con.host, con.err)
}
}
return nil
}
func (p *Pssh) printSortResults(ctx context.Context, results chan *result, cws []*conWork) int {
var firstCode int
resSlise := make([]*result, len(cws))
cur := 0
for i := 0; i < len(cws); i++ {
select {
case res := <-results:
resSlise[res.conID] = res
L1:
for j := cur; j < len(cws); j++ {
if resSlise[j] == nil {
break L1
}
p.printResult(resSlise[j], cws[resSlise[j].conID].host)
cur = j + one
if firstCode == 0 && resSlise[j].code != 0 {
firstCode = resSlise[j].code
}
}
case <-ctx.Done():
firstCode = one
}
}
return firstCode
}
func (p *Pssh) outputFunc() func(ctx context.Context, results chan *result, cws []*conWork) int {
if p.SortPrint {
return p.printSortResults
}
return p.printResults
}
func (p *Pssh) printResults(ctx context.Context, results chan *result, cws []*conWork) int {
var firstCode int
for i := 0; i < len(cws); i++ {
select {
case res := <-results:
p.printResult(res, cws[res.conID].host)
if firstCode == 0 && res.code != 0 {
firstCode = res.code
}
p.delReslt(res)
case <-ctx.Done():
firstCode = one
}
}
return firstCode
}
func (p *Pssh) printResult(res *result, host string) {
if p.ShowHostName {
var c prn
if res.code != 0 || res.err != nil {
c = p.boldRed
} else {
c = p.green
}
// nolint: errcheck,gosec
c.Printf("%s result code %d\n", host, res.code)
}
if res.err != nil {
// nolint: errcheck,gosec
e := res.err.Error()
if !strings.HasSuffix(e, "\n") {
e += "\n"
}
p.red.Printf("result err: %s", e)
}
if res.stdout.Len() > 0 {
// nolint: errcheck,gosec
res.stdout.WriteTo(os.Stdout)
}
if res.stderr.Len() > 0 {
// nolint: errcheck,gosec
p.red.Print(res.stderr.String())
}
}
type client interface {
NewSession() (*ssh.Session, error)
}
func getErr(ctx context.Context, errCh <-chan error) error {
var err error
L1:
for {
select {
case e, ok := <-errCh:
if !ok {
break L1
}
err = e
case <-ctx.Done():
return err
}
}
return err
}
func readStream(ctx context.Context, out io.Writer, r io.Reader, errCh chan<- error) {
_, err := io.Copy(out, r)
select {
case errCh <- err:
case <-ctx.Done():
}
close(errCh)
}
func (p *Pssh) sshKeyAgentCallback() ssh.AuthMethod {
if p.conns == nil {
return nil
}
agentClient := newAgentClient(p.conns)
return ssh.PublicKeysCallback(agentClient.Signers)
}
func (p *Pssh) mergeAuthMethods(identMethods []ssh.AuthMethod) []ssh.AuthMethod {
res := make([]ssh.AuthMethod, 0, len(identMethods)+one)
if !p.IdentityFileOnly {
if keyAgentMehod := p.sshKeyAgentCallback(); keyAgentMehod != nil {
res = append(res, keyAgentMehod)
}
}
return append(res, identMethods...)
}
func (p *Pssh) getIdentFileAuthMethods(identFileData [][]byte) []ssh.AuthMethod {
res := make([]ssh.AuthMethod, 0, len(identFileData))
for _, data := range identFileData {
key, err := ssh.ParsePrivateKey(data)
if err != nil {
continue
}
res = append(res, ssh.PublicKeys(key))
}
return res
}
func (p *Pssh) readIdentFiles() [][]byte {
res := make([][]byte, 0, len(p.IdentFiles))
home := os.Getenv("HOME")
for _, filePath := range p.IdentFiles {
// nolint: gosec
filePath = strings.Replace(filePath, "~", home, one)
buffer, err := ioutil.ReadFile(filePath)
if err != nil {
continue
}
res = append(res, buffer)
}
return res
}