/
ssh.go
57 lines (53 loc) · 1.4 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
package main
import (
"bytes"
"fmt"
"strings"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
)
// sshInteract runs an interactive command via SSH
func sshInteract(addr, user, pass, cmd, stdin string) (string, error) {
client, err := ssh.Dial("tcp", addr, &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.Password(pass),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
BannerCallback: ssh.BannerDisplayStderr(),
})
if err != nil {
return "", errors.Wrapf(err, "Failed to SSH to '%s'", addr)
}
defer client.Close()
out, err := runCommand(client, cmd, stdin)
if err != nil {
return "", err
}
return out, nil
}
func runCommand(client *ssh.Client, command, stdin string) (string, error) {
sess, err := client.NewSession()
if err != nil {
return "", err
}
defer sess.Close()
var b bytes.Buffer
var e bytes.Buffer
if stdin != "" {
command = fmt.Sprintf("%s\n%s\n", command, stdin)
} else {
command = fmt.Sprintf("%s\n", command)
}
sess.Stdin = strings.NewReader(command)
sess.Stdout = &b
sess.Stderr = &e
if err = sess.Shell(); err != nil /* .Start(command); err != nil */ {
return "", errors.Wrapf(err, "Failed to run command '%s' through remote shell", command)
}
if err = sess.Wait(); err != nil {
return "", errors.Wrapf(err, "Failed to finish command '%s'", command)
}
combined := strings.Join([]string{b.String(), e.String()}, "")
return combined, nil
}