forked from Juniper/go-netconf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
73 lines (60 loc) · 1.91 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
package netconf
import (
"io"
"golang.org/x/crypto/ssh"
)
// TODO: we may want to do some of the fancy concurrency stuff our SFTP client does, but we should probably refactor
// the code behind that so we can reuse it here instead of reinventing the wheel.
// Client works quite a lot like SFTP, which is also a subsystem of SSH
type Client struct {
session *Session
}
// NewClient is the constructor for Client. It creates a Client with stdin and stdout as the Reader and WriteCloser
func NewClient(conn *ssh.Client) (*Client, error) {
// establish ssh session
session, err := conn.NewSession()
if err != nil {
return nil, err
}
// request netconf subsystem from remote
if err = session.RequestSubsystem(SSHNetconfSubsystem); err != nil {
return nil, err
}
// set up stdin and stdout pipes
pw, err := session.StdinPipe()
if err != nil {
return nil, err
}
pr, err := session.StdoutPipe()
if err != nil {
return nil, err
}
return NewClientPipe(conn, session, pr, pw)
}
// NewClientPipe creates a Client using the given Reader and WriteCloser
func NewClientPipe(sshClient *ssh.Client, sshSession *ssh.Session, r io.Reader, w io.WriteCloser) (*Client, error) {
// set up transport using the given reader and writecloser
transport := TransportSSHFromSSHClient(sshClient, sshSession)
transport.ReadWriteCloser = NewTransportReadWriteCloser(r, w)
ncSession, err := NewSession(transport)
if err != nil {
return nil, err
}
// set up the client with a new netconf session
netconf := &Client{
session: ncSession,
}
return netconf, nil
}
// Close closes the netconf session to which the Client is connected
func (c *Client) Close() error {
return c.session.Close()
}
// GetConfig issues a request to netconf for configuration data.
func (c *Client) GetConfig(typ string) ([]byte, error) {
reply, err := c.session.Exec(MethodGetConfig(typ))
if err != nil {
return nil, err
}
return []byte(reply.Data), nil
}