/
host.go
83 lines (66 loc) · 1.44 KB
/
host.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
package host
import (
"errors"
"log"
"net"
"os"
"strings"
"time"
"golang.org/x/crypto/ssh"
)
type Host struct {
Addr string
username string
clientConfig *ssh.ClientConfig
// TODO: separate out to HostConnection
Connection *ssh.Client
}
func NewHost(connectionStr string, privateKeyPath string) (*Host, error) {
spl := strings.Split(connectionStr, "@")
if len(spl) < 2 {
return nil, errors.New("you must provide a username and an address for the host")
}
hostPort := spl[1]
spl2 := strings.Split(hostPort, ":")
host := spl2[0]
port := "22"
if len(spl2) > 1 {
port = spl2[1]
}
username := spl[0]
keyBytes, err := os.ReadFile(privateKeyPath)
if err != nil {
return nil, err
}
key, err := ssh.ParseRawPrivateKey(keyBytes)
if err != nil {
log.Fatalf("unable to parse private key: %s", err)
}
signer, err := ssh.NewSignerFromKey(key)
if err != nil {
return nil, err
}
return &Host{
Addr: net.JoinHostPort(host, port),
username: username,
clientConfig: &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: 5 * time.Second,
},
}, nil
}
func (h *Host) Connect() (*ssh.Client, error) {
client, err := ssh.Dial("tcp", h.Addr, h.clientConfig)
if err != nil {
return nil, err
}
h.Connection = client
return client, nil
}
func (h *Host) Close() error {
return h.Connection.Close()
}