-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
63 lines (48 loc) · 1.28 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
package gsh
import (
"context"
"errors"
"fmt"
"net"
"golang.org/x/crypto/ssh"
)
var ErrConfigNotFound = errors.New("config not found")
type contextKey struct {
string
}
var (
ConfigKey = contextKey{"ssh-config"}
ConnKey = contextKey{"ssh-conn"}
ClientKey = contextKey{"ssh-client"}
)
type (
ConfigCallback func(ctx context.Context, network, addr string) (*Config, error)
DialContext func(ctx context.Context, network, addr string) (net.Conn, error)
)
type Client struct {
ConfigCallback
DialContext
}
func (c *Client) Connect(ctx context.Context, network, address string) (Conn, error) {
cfg, err := c.ConfigCallback(ctx, network, address)
if err != nil {
return nil, fmt.Errorf("config callback error: %w", err)
}
ctx = context.WithValue(ctx, ConfigKey, cfg)
tcpConn, err := c.DialContext(ctx, cfg.Network, cfg.Address)
if err != nil {
return nil, fmt.Errorf("dial error: %w", err)
}
sshConn, chans, reqs, err := ssh.NewClientConn(tcpConn, cfg.Address, &cfg.ClientConfig)
if err != nil {
return nil, fmt.Errorf("ssh connection error: %w", err)
}
ctx = context.WithValue(ctx, ConnKey, sshConn)
sshCli := ssh.NewClient(sshConn, chans, reqs)
ctx = context.WithValue(ctx, ClientKey, sshCli)
return &conn{
ctx: ctx,
conn: sshConn,
cli: sshCli,
}, nil
}