forked from blacknon/go-sshlib
/
connect.go
271 lines (222 loc) · 6.33 KB
/
connect.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
// Copyright (c) 2021 Blacknon. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
package sshlib
import (
"io"
"net"
"os"
"os/signal"
"syscall"
"time"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/net/proxy"
"golang.org/x/term"
)
// Connect structure to store contents about ssh connection.
type Connect struct {
// Client *ssh.Client
Client *ssh.Client
// Session
Session *ssh.Session
// Session Stdin, Stdout, Stderr...
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
// ProxyDialer
ProxyDialer proxy.Dialer
// Connect timeout second.
ConnectTimeout int
// SendKeepAliveMax and SendKeepAliveInterval
SendKeepAliveMax int
SendKeepAliveInterval int
// Session use tty flag.
TTY bool
// Forward ssh agent flag.
ForwardAgent bool
// CheckKnownHosts if true, check knownhosts.
CheckKnownHosts bool
// OverwriteKnownHosts if true, if the knownhost is different, check whether to overwrite.
OverwriteKnownHosts bool
// KnownHostsFiles is list of knownhosts files path.
KnownHostsFiles []string
// TextAskWriteKnownHosts defines a confirmation message when writing a knownhost.
// We are using Go's template engine and have the following variables available.
// - Address ... ssh server hostname
// - RemoteAddr ... ssh server address
// - Fingerprint ... ssh PublicKey fingerprint
TextAskWriteKnownHosts string
// TextAskOverwriteKnownHosts defines a confirmation message when over-writing a knownhost.
// We are using Go's template engine and have the following variables available.
// - Address ... ssh server hostname
// - RemoteAddr ... ssh server address
// - OldKeyText ... old ssh PublicKey text.
// ex: /home/user/.ssh/known_hosts:17: ecdsa-sha2-nistp256 AAAAE2VjZHN...bJklasnFtkFSDyOjTFSv2g=
// - NewFingerprint ... new ssh PublicKey fingerprint
TextAskOverwriteKnownHosts string
// ssh-agent interface.
// agent.Agent or agent.ExtendedAgent
Agent AgentInterface
// Forward x11 flag.
ForwardX11 bool
// Version contains the version identification string that will
// be used for the connection. If empty, a reasonable default is used.
Version string
// HostKeyCallback is the function type used for verifying server keys.
// A HostKeyCallback must return nil if the host key is OK, or an error to reject it.
// It receives the hostname as passed to Dial or NewClientConn.
// The remote address is the RemoteAddr of the net.Conn underlying the SSH connection.
HostKeyCallback ssh.HostKeyCallback
// shell terminal log flag
logging bool
// terminal log add timestamp flag
logTimestamp bool
// terminal log path
logFile string
// remove ansi code on terminal log.
logRemoveAnsiCode bool
}
// CreateClient set c.Client.
func (c *Connect) CreateClient(host, port, user string, authMethods []ssh.AuthMethod) (err error) {
uri := net.JoinHostPort(host, port)
timeout := 20
if c.ConnectTimeout > 0 {
timeout = c.ConnectTimeout
}
// Create new ssh.ClientConfig{}
config := &ssh.ClientConfig{
User: user,
Auth: authMethods,
Timeout: time.Duration(timeout) * time.Second,
}
if c.CheckKnownHosts {
if len(c.KnownHostsFiles) == 0 {
// append default files
c.KnownHostsFiles = append(c.KnownHostsFiles, "~/.ssh/known_hosts")
}
config.HostKeyCallback = c.verifyAndAppendNew
} else {
if c.HostKeyCallback == nil {
config.HostKeyCallback = ssh.InsecureIgnoreHostKey()
} else {
config.HostKeyCallback = c.HostKeyCallback
}
}
if c.Agent != nil {
switch ag := c.Agent.(type) {
case agent.ExtendedAgent:
config.Auth = append(config.Auth, ssh.PublicKeysCallback(ag.Signers))
case agent.Agent:
config.Auth = append(config.Auth, ssh.PublicKeysCallback(ag.Signers))
}
}
// check Dialer
if c.ProxyDialer == nil {
c.ProxyDialer = proxy.Direct
}
// Dial to host:port
netConn, err := c.ProxyDialer.Dial("tcp", uri)
if err != nil {
return
}
// check Version
if c.Version != "" {
config.ClientVersion = "SSH-2.0-" + c.Version
}
// Create new ssh connect
sshCon, channel, req, err := ssh.NewClientConn(netConn, uri, config)
if err != nil {
return
}
// Create *ssh.Client
c.Client = ssh.NewClient(sshCon, channel, req)
return
}
// CreateSession retrun ssh.Session
func (c *Connect) CreateSession() (session *ssh.Session, err error) {
// Create session
session, err = c.Client.NewSession()
return
}
// SendKeepAlive send packet to session.
// TODO(blacknon): Interval及びMaxを設定できるようにする(v0.1.1)
func (c *Connect) SendKeepAlive(session *ssh.Session) {
// keep alive interval (default 30 sec)
interval := 30
if c.SendKeepAliveInterval > 0 {
interval = c.SendKeepAliveInterval
}
// keep alive max (default 5)
max := 5
if c.SendKeepAliveMax > 0 {
max = c.SendKeepAliveMax
}
// keep alive counter
i := 0
for {
// Send keep alive packet
_, err := session.SendRequest("keepalive", true, nil)
// _, _, err := c.Client.SendRequest("keepalive", true, nil)
if err == nil {
i = 0
} else {
i += 1
}
// check counter
if max <= i {
session.Close()
return
}
// sleep
time.Sleep(time.Duration(interval) * time.Second)
}
}
// CheckClientAlive check alive ssh.Client.
func (c *Connect) CheckClientAlive() error {
_, _, err := c.Client.SendRequest("keepalive", true, nil)
if err == nil || err.Error() == "request failed" {
return nil
}
return err
}
// RequestTty requests the association of a pty with the session on the remote
// host. Terminal size is obtained from the currently connected terminal
func RequestTty(session *ssh.Session) (err error) {
modes := ssh.TerminalModes{
ssh.ECHO: 1,
ssh.TTY_OP_ISPEED: 14400,
ssh.TTY_OP_OSPEED: 14400,
}
// Get terminal window size
fd := int(os.Stdout.Fd())
width, hight, err := term.GetSize(fd)
if err != nil {
return
}
// Get env `TERM`
xterm := os.Getenv("TERM")
if len(xterm) == 0 {
xterm = "xterm"
}
if err = session.RequestPty(xterm, hight, width, modes); err != nil {
session.Close()
return
}
// Terminal resize goroutine.
winch := syscall.Signal(0x1c)
signalchan := make(chan os.Signal, 1)
signal.Notify(signalchan, winch)
go func() {
for {
s := <-signalchan
switch s {
case winch:
fd := int(os.Stdout.Fd())
width, hight, _ = term.GetSize(fd)
session.WindowChange(hight, width)
}
}
}()
return
}