forked from scottkiss/gosshtool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtool.go
55 lines (48 loc) · 1.08 KB
/
tool.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
package gosshtool
import (
"errors"
"sync"
)
var (
sshClients map[string]*SSHClient
sshClientsMutex sync.RWMutex
)
func init() {
sshClients = make(map[string]*SSHClient)
}
func NewSSHClient(config *SSHClientConfig) (client *SSHClient) {
sshClientsMutex.RLock()
client = sshClients[config.Host]
if client != nil {
return
}
sshClientsMutex.RUnlock()
client = new(SSHClient)
client.Host = config.Host
client.User = config.User
client.Password = config.Password
client.Privatekey = config.Privatekey
sshClientsMutex.Lock()
sshClients[config.Host] = client
sshClientsMutex.Unlock()
return client
}
func getClient(hostname string) (client *SSHClient, err error) {
if hostname == "" {
return nil, errors.New("host name is empty")
}
sshClientsMutex.RLock()
client = sshClients[hostname]
if client != nil {
return client, nil
}
sshClientsMutex.RUnlock()
return nil, errors.New("client not create")
}
func ExecuteCmd(cmd, hostname string) (output, errput string, err error) {
client, err := getClient(hostname)
if err != nil {
return
}
return client.Cmd(cmd)
}