/
ssh.go
85 lines (75 loc) · 2.48 KB
/
ssh.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
package testutil
import (
"io"
"net"
"strconv"
"testing"
sshd "github.com/gliderlabs/ssh"
"golang.org/x/crypto/ssh"
)
func SSHServer(t testing.TB) string {
t.Helper()
var handler sshd.Handler = func(s sshd.Session) {
_, _ = s.Write([]byte("Hello world\n"))
}
host := "127.0.0.1"
port := NewPort(t)
addr := net.JoinHostPort(host, strconv.Itoa(port))
ts := &sshd.Server{Addr: addr, Handler: handler}
opts := []sshd.Option{
sshd.PasswordAuth(func(ctx sshd.Context, password string) bool {
return true // allow all passwords
}),
sshd.PublicKeyAuth(func(ctx sshd.Context, key sshd.PublicKey) bool {
return true // allow all keys, or use ssh.KeysEqual() to compare against known keys
}),
}
for _, opt := range opts {
if err := ts.SetOption(opt); err != nil {
t.Fatal(err)
}
}
ch := make(chan struct{})
go func() {
_ = ts.ListenAndServe()
close(ch)
}()
t.Cleanup(func() {
// FIXME: May not be able to Close successfully if there is never a connection
if err := ts.Close(); err != nil {
t.Fatal(err)
}
<-ch
})
return addr
}
func NewNullSSHClient() *ssh.Client {
return ssh.NewClient(&NullConn{}, nil, nil)
}
type NullConn struct{}
func (*NullConn) User() string { return "" }
func (*NullConn) SessionID() []byte { return nil }
func (*NullConn) ClientVersion() []byte { return nil }
func (*NullConn) ServerVersion() []byte { return nil }
func (*NullConn) RemoteAddr() net.Addr { return nil }
func (*NullConn) LocalAddr() net.Addr { return nil }
func (*NullConn) SendRequest(name string, wantReply bool, payload []byte) (bool, []byte, error) {
return true, nil, nil
}
func (*NullConn) OpenChannel(name string, data []byte) (ssh.Channel, <-chan *ssh.Request, error) {
return &NullChannel{}, nil, nil
}
func (*NullConn) Close() error { return nil }
func (*NullConn) Wait() error { return nil }
type NullChannel struct{}
func (*NullChannel) Read(data []byte) (int, error) { return 10, nil }
func (*NullChannel) Write(data []byte) (int, error) { return 10, nil }
func (*NullChannel) Close() error { return nil }
func (*NullChannel) CloseWrite() error { return nil }
func (*NullChannel) SendRequest(name string, wantReply bool, payload []byte) (bool, error) {
return true, nil
}
func (*NullChannel) Stderr() io.ReadWriter { return &NullReadWriter{} }
type NullReadWriter struct{}
func (*NullReadWriter) Read(data []byte) (int, error) { return 10, nil }
func (*NullReadWriter) Write(data []byte) (int, error) { return 10, nil }