-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathossh_dispatcher.go
94 lines (89 loc) · 2.17 KB
/
ossh_dispatcher.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
package main
import (
"errors"
"fmt"
"strings"
"golang.org/x/crypto/ssh"
)
// OsshDisaptcher ...
type OsshDisaptcher struct {
par int
command string
sshClientConfig *ssh.ClientConfig
hosts []OsshHost
preconnect bool
ignoreFailures bool
socks5ProxyAddr string
retryCount int
jumpHostAddr string
}
func (d *OsshDisaptcher) validate() error {
var errList []string
if d.par < 1 {
errList = append(errList, "parallelism should be > 0")
}
if len(d.command) == 0 {
errList = append(errList, "no command is specified")
}
if len(d.hosts) == 0 {
errList = append(errList, "host list is empty")
}
if len(errList) > 0 {
return errors.New(strings.Join(errList, "\n"))
}
return nil
}
func (d *OsshDisaptcher) run() error {
var failureCount int
hostIdx := 0
c := make(chan *OsshMessage)
if d.preconnect {
for hostIdx = 0; hostIdx < len(d.hosts); hostIdx++ {
go (&d.hosts[hostIdx]).sshConnect(c, d.sshClientConfig, d.socks5ProxyAddr, d.retryCount, d.jumpHostAddr)
}
for hostIdx = 0; hostIdx < len(d.hosts); hostIdx++ {
message, ok := <-c
if ok == false {
return fmt.Errorf("channel got closed unexpectedly, exiting")
}
if (message.messageType & ERROR) != 0 {
message.println()
failureCount++
} else if (message.messageType & VERBOSE) != 0 {
message.println()
}
}
}
if !d.ignoreFailures && failureCount > 0 {
return fmt.Errorf("failed to connect to %d hosts, exiting", failureCount)
}
running := 0
for hostIdx = 0; hostIdx < len(d.hosts) && running < d.par; hostIdx++ {
if d.hosts[hostIdx].err != nil {
continue
}
go (&d.hosts[hostIdx]).sshRun(c, d.sshClientConfig, d.command, d.socks5ProxyAddr, d.retryCount, d.jumpHostAddr)
running++
}
for running > 0 {
message, ok := <-c
if ok == false {
break
}
if (message.messageType & ERROR) != 0 {
message.println()
running--
} else if (message.messageType & CLOSE) != 0 {
running--
} else {
message.println()
continue
}
if hostIdx < len(d.hosts) {
go (&d.hosts[hostIdx]).sshRun(c, d.sshClientConfig, d.command, d.socks5ProxyAddr, d.retryCount, d.jumpHostAddr)
running++
hostIdx++
}
}
return nil
}