forked from 0xef53/go-sshwrapper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sshwrapper.go
242 lines (205 loc) · 5.2 KB
/
sshwrapper.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package sshwrapper
import (
"context"
"fmt"
"io"
"net"
"strconv"
"strings"
"time"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
// ConnTimeout specifies the maximum amount of time for the TCP connection to establish
var ConnTimeout = 60 * time.Second
// A SSHConn represents a connection to run remote commands.
type SSHConn struct {
client *ssh.Client
agentConn net.Conn
forwardAgent bool
envs map[string]string
}
// Dial creates a client connection to the given SSH server.
//
// `addr` should be provided in the following format:
//
// user@host:port
//
// if `forwardAgent` is true then forwarding of the authentication agent connection will be enabled.
func Dial(addr string, socket string, forwardAgent bool) (*SSHConn, error) {
agentConn, err := net.Dial("unix", socket)
if err != nil {
return nil, err
}
var agentOk bool
defer func() {
if !agentOk {
agentConn.Close()
}
}()
sshAgent := agent.NewClient(agentConn)
signers, err := sshAgent.Signers()
if err != nil {
return nil, err
}
host, port, user, err := ParseAddr(addr)
if err != nil {
return nil, err
}
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{ssh.PublicKeys(signers...)},
Timeout: ConnTimeout,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", host, port), config)
if err != nil {
return nil, err
}
var clientOk bool
defer func() {
if !clientOk {
client.Close()
}
}()
if forwardAgent {
if err := agent.ForwardToAgent(client, sshAgent); err != nil {
return nil, fmt.Errorf("SetupForwardKeyring: %v", err)
}
}
agentOk = true
clientOk = true
c := SSHConn{
client: client,
agentConn: agentConn,
forwardAgent: forwardAgent,
}
return &c, nil
}
// Close closes the connection
func (s *SSHConn) Close() {
s.agentConn.Close()
s.client.Close()
}
func (s *SSHConn) requestAgentForwarding(session *ssh.Session) error {
if !s.forwardAgent {
return nil
}
if err := agent.RequestAgentForwarding(session); err != nil {
return fmt.Errorf("RequestAgentForwarding: %v", err)
}
return nil
}
// Output runs cmd on the remote host and returns its standard output.
func (s *SSHConn) Output(cmd string, in io.Reader) ([]byte, error) {
session, err := s.client.NewSession()
if err != nil {
return nil, err
}
defer session.Close()
if err := s.requestAgentForwarding(session); err != nil {
return nil, err
}
for k, v := range s.envs {
if err := session.Setenv(k, v); err != nil {
return nil, err
}
}
session.Stdin = in
return session.Output(cmd)
}
// CombinedOutput runs cmd on the remote host and returns its combined standard output and standard error.
func (s *SSHConn) CombinedOutput(cmd string, in io.Reader) ([]byte, error) {
session, err := s.client.NewSession()
if err != nil {
return nil, err
}
defer session.Close()
if err := s.requestAgentForwarding(session); err != nil {
return nil, err
}
for k, v := range s.envs {
if err := session.Setenv(k, v); err != nil {
return nil, err
}
}
session.Stdin = in
return session.CombinedOutput(cmd)
}
// Run runs cmd on the remote host.
//
// See https://godoc.org/golang.org/x/crypto/ssh#Session.Run for details.
func (s *SSHConn) RunContext(ctx context.Context, cmd string, in io.Reader, outWriter, errWriter io.Writer) error {
session, err := s.client.NewSession()
if err != nil {
return err
}
defer session.Close()
if err = s.requestAgentForwarding(session); err != nil {
return err
}
for k, v := range s.envs {
if err = session.Setenv(k, v); err != nil {
return err
}
}
session.Stdout = outWriter
session.Stderr = errWriter
session.Stdin = in
exit := make(chan struct{}, 1)
defer close(exit)
go func() {
select {
case <-ctx.Done():
if ctx.Err() != nil {
session.Signal(ssh.SIGINT)
session.Close()
}
case <-exit:
}
}()
err = session.Run(cmd)
return err
}
func (s *SSHConn) Run(cmd string, in io.Reader, outWriter, errWriter io.Writer) error {
return s.RunContext(context.Background(), cmd, in, outWriter, errWriter)
}
// SetEnvs specifies the environment that will be applied
// to any command executed by Output/CombinedOutput/Run.
func (s *SSHConn) SetEnvs(e map[string]string) {
s.envs = e
}
// ParseAddr parses SSH connection string and if everything is correct
// returns three separate values -- host, port and user.
func ParseAddr(s string) (host string, port int, user string, err error) {
port = 22
user = "root"
origAddr := s
switch fields := strings.Split(s, "@"); {
case len(fields) == 1:
case len(fields) == 2:
if len(fields[1]) == 0 {
return "", 0, "", fmt.Errorf("incorrect addr format: %s", origAddr)
}
user, s = fields[0], fields[1]
default:
return "", 0, "", fmt.Errorf("incorrect addr format: %s", origAddr)
}
switch fields := strings.Split(s, ":"); {
case len(fields) == 1:
host = fields[0]
case len(fields) == 2:
if len(fields[1]) == 0 {
return "", 0, "", fmt.Errorf("incorrect addr format: %s", origAddr)
}
host = fields[0]
d, err := strconv.Atoi(fields[1])
if err != nil {
return "", 0, "", err
}
port = d
default:
return "", 0, "", fmt.Errorf("incorrect addr format: %s", origAddr)
}
return
}