-
Notifications
You must be signed in to change notification settings - Fork 1
/
ssh.go
95 lines (84 loc) · 1.71 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
86
87
88
89
90
91
92
93
94
95
package main
import (
"bytes"
"context"
"fmt"
"os"
"os/user"
"strings"
"golang.org/x/crypto/ssh"
)
var routes = map[string]struct{}{
"up": {},
"down": {},
"stop": {},
"start": {},
"restart": {},
"ps": {},
"pull": {},
"logs": {},
"exec": {},
"load": {},
"git": {},
"journal": {},
"ping": {},
}
func querySSH(ctx context.Context, machine, command string, args []string) ([]byte, error) {
var (
key []byte
err error
)
ident := ctx.Value("i").(string)
switch ident {
default:
key, err = os.ReadFile(ident)
if err != nil {
return nil, err
}
case "":
key, err = IDFromEnv()
if err != nil {
return nil, fmt.Errorf("identity not given, -i flag; %v", err)
}
}
port := ctx.Value("p").(string)
if port == "" {
port = "2222"
}
// 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", machine+":"+port, config)
if err != nil {
return nil, err
}
defer client.Close()
ss, err := client.NewSession()
if err != nil {
return nil, err
}
defer ss.Close()
stdoutBuf := &bytes.Buffer{}
ss.Stdout = stdoutBuf
cmdline := command + " " + strings.Join(args, " ")
err = ss.Run(cmdline)
return stdoutBuf.Bytes(), err
}
func IDFromEnv() ([]byte, error) {
key := os.Getenv("PGOCTL_ID")
if key == "" {
return nil, fmt.Errorf("no enviroment variable found with name: %q", "PGOCTL_ID")
}
return []byte(key), nil
}