forked from gliderlabs/hostctl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh.go
59 lines (53 loc) · 1.15 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
package main
import (
"fmt"
"os"
"os/exec"
"syscall"
"github.com/progrium/hostctl/providers"
"github.com/spf13/cobra"
)
func init() {
Hostctl.AddCommand(sshCmd)
}
var sshCmd = &cobra.Command{
Use: "ssh <name> [--] [<command>...]",
Short: "SSH to host",
Run: func(cmd *cobra.Command, args []string) {
if len(args) < 1 && defaultName == "" {
cmd.Usage()
os.Exit(1)
}
name, sshCmd := sshParseArgs(args)
provider, err := providers.Get(providerName, true)
fatal(err)
host := provider.Get(namespace + name)
if host == nil {
os.Exit(1)
}
fatal(sshExec(host.IP, sshCmd))
},
}
func sshExec(ip string, cmd []string) error {
binary, err := exec.LookPath("ssh")
if err != nil {
return fmt.Errorf("Unable to find ssh")
}
args := []string{"ssh", "-A", "-l", sshUser, ip}
return syscall.Exec(binary, append(args, cmd...), os.Environ())
}
func sshParseArgs(args []string) (string, []string) {
var name string
var sshCmd []string
if len(args) == 0 || args[0] == "--" {
name = defaultName
sshCmd = args
} else {
name = args[0]
sshCmd = args[1:]
}
if optArg(sshCmd, 0, "") == "--" {
sshCmd = sshCmd[1:]
}
return name, sshCmd
}