/
ssh.go
67 lines (57 loc) · 1.25 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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os/user"
"strings"
"github.com/urfave/cli/v2"
"golang.org/x/crypto/ssh"
)
func querySSH(ctx *cli.Context, at, command string, args ...string) ([]byte, error) {
ident := ctx.String("i")
if ident == "" {
return nil, fmt.Errorf("identity file not given, -i flag")
}
port := ctx.String("p")
if port == "" {
port = "2222"
}
at = at + ":" + port
key, err := ioutil.ReadFile(ident)
if err != nil {
return nil, err
}
// Create the Signer for this private key.
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
return nil, err
}
user, err := user.Current()
if err != nil {
return nil, err
}
config := &ssh.ClientConfig{
User: user.Username,
Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, err := ssh.Dial("tcp", at, config)
if err != nil {
return nil, err
}
defer client.Close()
ss, err := client.NewSession()
if err != nil {
return nil, err
}
defer ss.Close()
// makes this buffer bounded...?
stdoutBuf := &bytes.Buffer{}
ss.Stdout = stdoutBuf
cmdline := command + " " + strings.Join(args, " ")
if err := ss.Run(cmdline); err != nil {
return nil, err
}
return stdoutBuf.Bytes(), nil
}