-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh_facade.go
68 lines (61 loc) · 1.44 KB
/
ssh_facade.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
package main
import (
"errors"
"github.com/creack/pty"
"golang.org/x/crypto/ssh/terminal"
"io"
"log"
"os"
"os/exec"
"os/signal"
"syscall"
)
type SshFacade struct {
ip string
env string
stageKey string
prodKey string
}
func (ssh *SshFacade) Connect() {
pathToKey, err := ssh.pathToKey()
if err != nil {
log.Fatal(err)
}
cmd := exec.Command("ssh", "-i"+pathToKey, "ubuntu@"+ssh.ip)
// Start the command with a pty.
ptmx, err := pty.Start(cmd)
if err != nil {
log.Fatal(err)
}
// Make sure to close the pty at the end.
defer func() { _ = ptmx.Close() }() // Best effort.
// Handle pty size.
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGWINCH)
go func() {
for range ch {
if err := pty.InheritSize(os.Stdin, ptmx); err != nil {
log.Printf("error resizing pty: %s", err)
}
}
}()
ch <- syscall.SIGWINCH // Initial resize.
// Set stdin in raw mode.
oldState, err := terminal.MakeRaw(int(os.Stdin.Fd()))
if err != nil {
panic(err)
}
defer func() { _ = terminal.Restore(int(os.Stdin.Fd()), oldState) }() // Best effort.
// Copy stdin to the pty and the pty to stdout.
go func() { _, _ = io.Copy(ptmx, os.Stdin) }()
_, _ = io.Copy(os.Stdout, ptmx)
}
func (ssh *SshFacade) pathToKey() (key string, err error) {
if ssh.env == "stg" {
return ssh.stageKey, nil
} else if ssh.env == "prod" {
return ssh.prodKey, nil
} else {
return "", errors.New("Key for env '" + ssh.env + "' not found")
}
}