-
Notifications
You must be signed in to change notification settings - Fork 231
/
client.go
125 lines (107 loc) · 2.42 KB
/
client.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
package ssh
import (
"bytes"
"errors"
"fmt"
"net"
"os"
"strconv"
"time"
log "github.com/crc-org/crc/v2/pkg/crc/logging"
"golang.org/x/crypto/ssh"
)
type Client interface {
Run(command string) ([]byte, []byte, error)
Close()
}
type NativeClient struct {
User string
Hostname string
Port int
Keys []string
conn *ssh.Client
}
func NewClient(user string, host string, port int, keys ...string) (Client, error) {
return &NativeClient{
User: user,
Hostname: host,
Port: port,
Keys: keys,
}, nil
}
func clientConfig(user string, keys []string) (*ssh.ClientConfig, error) {
var (
privateKeys []ssh.Signer
keyPaths []string
)
for _, k := range keys {
key, err := os.ReadFile(k)
if err != nil {
continue
}
privateKey, err := ssh.ParsePrivateKey(key)
if err != nil {
return nil, err
}
privateKeys = append(privateKeys, privateKey)
keyPaths = append(keyPaths, k)
}
if len(privateKeys) == 0 {
return nil, errors.New("no ssh private keys available")
}
log.Debugf("Using ssh private keys: %v", keyPaths)
return &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{ssh.PublicKeys(privateKeys...)},
// #nosec G106
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: 10 * time.Second,
}, nil
}
func (client *NativeClient) session() (*ssh.Session, error) {
if client.conn == nil {
var err error
config, err := clientConfig(client.User, client.Keys)
if err != nil {
return nil, fmt.Errorf("Error getting config for native Go SSH: %s", err)
}
client.conn, err = ssh.Dial("tcp", net.JoinHostPort(client.Hostname, strconv.Itoa(client.Port)), config)
if err != nil {
return nil, err
}
}
session, err := client.conn.NewSession()
if err != nil {
return nil, err
}
return session, err
}
func (client *NativeClient) Run(command string) ([]byte, []byte, error) {
session, err := client.session()
if err != nil {
if client.conn != nil {
log.Debugf("Failed to create new ssh session: %s", err)
client.conn.Close()
client.conn = nil
}
return nil, nil, err
}
defer session.Close()
var (
stdout bytes.Buffer
stderr bytes.Buffer
)
session.Stdout = &stdout
session.Stderr = &stderr
err = session.Run(command)
return stdout.Bytes(), stderr.Bytes(), err
}
func (client *NativeClient) Close() {
if client.conn == nil {
return
}
err := client.conn.Close()
if err != nil {
log.Debugf("Error closing ssh client: %s", err)
}
}