forked from kubernetes-retired/bootkube
/
ssh_client.go
88 lines (70 loc) · 1.96 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
83
84
85
86
87
88
package e2e
import (
"bytes"
"io/ioutil"
"log"
"net"
"os"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
// The global SSH client used by the tests.
var sshClient *SSHClient
type SSHClient struct {
*ssh.ClientConfig
}
func InitSSHClient(keypath string) {
sshClient = newSSHClientOrDie(keypath)
}
// newSSHClientOrDie tries to create an ssh client.
// If $SSH_AUTH_SOCK is set, the use the ssh agent to create the client,
// otherwise read the private key directly.
func newSSHClientOrDie(keypath string) *SSHClient {
var authMethod ssh.AuthMethod
sock := os.Getenv("SSH_AUTH_SOCK")
if sock != "" {
log.Println("Creating ssh client with ssh agent")
sshAgent, err := net.Dial("unix", sock)
if err != nil {
panic(err)
}
authMethod = ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers)
} else {
log.Println("Creating ssh client with private key")
key, err := ioutil.ReadFile(keypath)
if err != nil {
panic(err)
}
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
panic(err)
}
authMethod = ssh.PublicKeys(signer)
}
sshConfig := &ssh.ClientConfig{
User: "core", // TODO(yifan): Assume all nodes are container linux nodes for now.
Auth: []ssh.AuthMethod{authMethod},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
return &SSHClient{sshConfig}
}
func (c *SSHClient) SSH(host, cmd string) (stdout, stderr []byte, err error) {
client, err := ssh.Dial("tcp", host+":22", c.ClientConfig) // TODO(yifan): Assume all nodes are listening on :22 for ssh requests for now.
if err != nil {
return nil, nil, err
}
defer client.Conn.Close()
session, err := client.NewSession()
if err != nil {
return nil, nil, err
}
defer session.Close()
outBuf := bytes.NewBuffer(nil)
errBuf := bytes.NewBuffer(nil)
session.Stdout = outBuf
session.Stderr = errBuf
err = session.Run(cmd)
stdout = bytes.TrimSpace(outBuf.Bytes())
stderr = bytes.TrimSpace(errBuf.Bytes())
return stdout, stderr, err
}