/
ssh_client.go
82 lines (67 loc) · 1.83 KB
/
ssh_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
74
75
76
77
78
79
80
81
82
package providers
import (
"bytes"
"io"
"net"
"os"
"strings"
"github.com/juju/errgo"
logging "github.com/op/go-logging"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
type SSHClient interface {
io.Closer
Run(log *logging.Logger, command, stdin string, quiet bool) (string, error)
}
type sshClient struct {
client *ssh.Client
}
// DialSSH creates a new SSH connection to the given user on the given host.
func DialSSH(userName, host string) (SSHClient, error) {
// To authenticate with the remote server you must pass at least one
// implementation of AuthMethod via the Auth field in ClientConfig.
config := &ssh.ClientConfig{
User: userName,
}
var sshAgent agent.Agent
if agentConn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
sshAgent = agent.NewClient(agentConn)
config.Auth = append(config.Auth, ssh.PublicKeysCallback(sshAgent.Signers))
} else {
return nil, maskAny(err)
}
addr := net.JoinHostPort(host, "22")
client, err := ssh.Dial("tcp", addr, config)
if err != nil {
return nil, maskAny(err)
}
return &sshClient{client}, nil
}
func (s *sshClient) Close() error {
return maskAny(s.client.Close())
}
func (s *sshClient) Run(log *logging.Logger, command, stdin string, quiet bool) (string, error) {
var stdOut, stdErr bytes.Buffer
// Each ClientConn can support multiple interactive sessions,
// represented by a Session.
session, err := s.client.NewSession()
if err != nil {
return "", maskAny(err)
}
defer session.Close()
session.Stdout = &stdOut
session.Stderr = &stdErr
if stdin != "" {
session.Stdin = strings.NewReader(stdin)
}
if err := session.Run(command); err != nil {
if !quiet {
log.Errorf("SSH failed: %s", command)
}
return "", errgo.NoteMask(err, stdErr.String())
}
out := stdOut.String()
out = strings.TrimSuffix(out, "\n")
return out, nil
}