-
Notifications
You must be signed in to change notification settings - Fork 233
/
client.go
89 lines (71 loc) · 1.57 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
package ssh
import (
"context"
"errors"
"log"
"net"
"golang.org/x/crypto/ssh"
)
type Client struct {
Addr string
User string
Dial func(ctx context.Context, network, addr string) (net.Conn, error)
PrivateKey, Certificate string
client *ssh.Client
conn ssh.Conn
}
func (c *Client) Close() error {
if c.conn != nil {
if err := c.conn.Close(); err != nil {
return err
}
}
c.conn = nil
return nil
}
func (c *Client) Connect(ctx context.Context) error {
pubKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(c.Certificate))
cert, ok := pubKey.(*ssh.Certificate)
if !ok {
return errors.New("SSH public key must be a certificate")
}
keySigner, err := ssh.ParsePrivateKey([]byte(c.PrivateKey))
if err != nil {
return err
}
signer, err := ssh.NewCertSigner(cert, keySigner)
if err != nil {
log.Fatal(err)
}
tcpConn, err := c.Dial(ctx, "tcp", c.Addr)
if err != nil {
return err
}
conf := &ssh.ClientConfig{
User: c.User,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
HostKeyAlgorithms: []string{ssh.KeyAlgoED25519},
}
conn, chans, reqs, err := ssh.NewClientConn(tcpConn, tcpConn.RemoteAddr().String(), conf)
if err != nil {
return err
}
c.conn, c.client = conn, ssh.NewClient(conn, chans, reqs)
return nil
}
func (c *Client) Shell(ctx context.Context, term *Terminal) error {
if c.client == nil {
if err := c.Connect(ctx); err != nil {
return err
}
}
sess, err := c.client.NewSession()
if err != nil {
return err
}
defer sess.Close()
return term.attach(ctx, sess)
}