/
ssh.go
214 lines (196 loc) · 5.06 KB
/
ssh.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
package sshexec
import (
"errors"
"io/ioutil"
"log"
"os"
"strconv"
"strings"
"time"
"github.com/ivpusic/grpool"
"golang.org/x/crypto/ssh"
)
//
// Main agent struct
//
type SSHExecAgent struct {
Worker int
TimeOut time.Duration
}
func PublicKeyFile(file string) ssh.AuthMethod {
buffer, err := ioutil.ReadFile(file)
if err != nil {
log.Printf("PublicKeyFile err %s \r\n", err.Error())
return nil
}
key, err := ssh.ParsePrivateKey(buffer)
if err != nil {
log.Printf("ParsePrivateKey err %s \r\n", err.Error())
return nil
}
return ssh.PublicKeys(key)
}
func GetAuthPassword(password string) []ssh.AuthMethod {
return []ssh.AuthMethod{ssh.Password(password)}
}
func GetAuthKeys(keys []string) []ssh.AuthMethod {
methods := []ssh.AuthMethod{}
for _, keyname := range keys {
pkey := PublicKeyFile(keyname)
if pkey != nil {
methods = append(methods, pkey)
}
}
return methods
}
func (s *SSHExecAgent) SshHostByKey(hosts []string, user string, cmd string) ([]ExecResult, error) {
log.Printf("SshHostByKey %s %+v\r\n ", user, hosts)
if len(hosts) == 0 {
log.Println("no hosts")
return nil, errors.New("no hosts")
}
if s.Worker == 0 {
s.Worker = 40
}
if s.TimeOut == 0 {
s.TimeOut = 3600 * time.Second
}
keys := []string{
os.Getenv("HOME") + "/.ssh/id_dsa",
os.Getenv("HOME") + "/.ssh/id_rsa",
}
authKeys := GetAuthKeys(keys)
if len(authKeys) < 1 {
log.Println("the user no key")
return nil, errors.New("the user no key")
}
pool := grpool.NewPool(s.Worker, len(hosts), s.TimeOut)
defer pool.Release()
pool.WaitCount(len(hosts))
for i, _ := range hosts {
count := i
pool.JobQueue <- grpool.Job{
Jobid: count,
Jobfunc: func() (interface{}, error) {
hostInfo := strings.Split(hosts[count], ":")
ip := hostInfo[0]
prot := 22
if len(hostInfo) > 1 {
protInt, err := strconv.Atoi(hostInfo[1])
if err == nil {
prot = protInt
}
}
session := &HostSession{
Username: user,
Password: "",
Hostname: ip,
Port: prot,
Auths: authKeys,
}
r := session.Exec(count, cmd, session.GenerateConfig())
return *r, nil
},
}
}
pool.WaitAll()
returnResult := make([]ExecResult, len(hosts))
errorText := ""
for res := range pool.Jobresult {
jobId, _ := res.Jobid.(int)
if res.Timedout {
returnResult[jobId].Id = jobId
returnResult[jobId].Host = hosts[jobId]
returnResult[jobId].Command = cmd
returnResult[jobId].Error = errors.New("ssh time out")
errorText += "the host " + hosts[jobId] + " commond exec time out."
} else {
execResult, _ := res.Result.(ExecResult)
returnResult[jobId] = execResult
if execResult.Error != nil {
errorText += "the host " + execResult.Host + " commond exec error.\n" + "rsult info :" + execResult.Result + ".\nerror info :" + execResult.Error.Error()
}
}
}
if errorText != "" {
return returnResult, errors.New(errorText)
} else {
return returnResult, nil
}
}
//这里的host要带端口信息
func (s *SSHExecAgent) SftpHostByKey(hosts []string, user string, localFilePath string, remoteFilePath string) ([]ExecResult, error) {
if len(hosts) == 0 {
log.Println("no hosts")
return nil, errors.New("no hosts")
}
if s.Worker == 0 {
s.Worker = 40
}
if s.TimeOut == 0 {
s.TimeOut = 3600 * time.Second
}
keys := []string{
os.Getenv("HOME") + "/.ssh/id_dsa",
os.Getenv("HOME") + "/.ssh/id_rsa",
}
authKeys := GetAuthKeys(keys)
if len(authKeys) < 1 {
log.Println("the user no key")
return nil, errors.New("the user no key")
}
pool := grpool.NewPool(s.Worker, len(hosts), s.TimeOut)
defer pool.Release()
pool.WaitCount(len(hosts))
for i, _ := range hosts {
count := i
pool.JobQueue <- grpool.Job{
Jobid: count,
Jobfunc: func() (interface{}, error) {
hostInfo := strings.Split(hosts[count], ":")
ip := hostInfo[0]
prot := 22
if len(hostInfo) > 1 {
protInt, err := strconv.Atoi(hostInfo[1])
if err == nil {
prot = protInt
}
}
session := &HostSession{
Username: user,
Password: "",
Hostname: ip,
Port: prot,
Auths: authKeys,
}
r := session.Transfer(count, localFilePath, remoteFilePath, session.GenerateConfig())
return *r, nil
},
}
}
pool.WaitAll()
returnResult := make([]ExecResult, len(hosts))
errorText := ""
for res := range pool.Jobresult {
jobId, _ := res.Jobid.(int)
if res.Timedout {
returnResult[jobId].Id = jobId
returnResult[jobId].Host = hosts[jobId]
returnResult[jobId].LocalFilePath = localFilePath
returnResult[jobId].RemoteFilePath = remoteFilePath
returnResult[jobId].Error = errors.New("ssh time out")
errorText += "the host " + hosts[jobId] + " commond exec time out."
} else {
execResult, _ := res.Result.(ExecResult)
returnResult[jobId] = execResult
if execResult.Error != nil {
errorText += "the host " + execResult.Host + " commond exec error.\n" + "rsult info :" + execResult.Result + ".\nerror info :" + execResult.Error.Error()
}
}
}
if errorText != "" {
return returnResult, errors.New(errorText)
} else {
return returnResult, nil
}
}