-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathssh.go
More file actions
68 lines (63 loc) · 1.83 KB
/
ssh.go
File metadata and controls
68 lines (63 loc) · 1.83 KB
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 deisctl
import (
"fmt"
"os"
"os/exec"
"strings"
"syscall"
"github.com/coreos/fleet/machine"
"github.com/coreos/fleet/ssh"
)
// runCommand will attempt to run a command on a given machine
// It will attempt to SSH to the machine if it is identified as being remote.
func runCommand(cmd string, ms *machine.MachineState) (retcode int) {
var err error
if machine.IsLocalMachineState(ms) {
err, retcode = runLocalCommand(cmd)
if err != nil {
fmt.Printf("Error running local command: %v\n", err)
}
} else {
err, retcode = runRemoteCommand(cmd, ms.PublicIP)
if err != nil {
fmt.Printf("Error running remote command: %v\n", err)
}
}
return
}
// runLocalCommand runs the given command locally
// and returns any error encountered and the exit code of the command
func runLocalCommand(cmd string) (error, int) {
cmdSlice := strings.Split(cmd, " ")
osCmd := exec.Command(cmdSlice[0], cmdSlice[1:]...)
osCmd.Stderr = os.Stderr
osCmd.Stdout = os.Stdout
osCmd.Start()
err := osCmd.Wait()
if err != nil {
// Get the command's exit status if we can
if exiterr, ok := err.(*exec.ExitError); ok {
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
return nil, status.ExitStatus()
}
}
// Otherwise, generic command error
return err, -1
}
return nil, 0
}
// runRemoteCommand runs the given command over SSH on the given IP
// and returns any error encountered and the exit status of the command
func runRemoteCommand(cmd string, addr string) (err error, exit int) {
var sshClient *ssh.SSHForwardingClient
if tun := getTunnelFlag(); tun != "" {
sshClient, err = ssh.NewTunnelledSSHClient("core", tun, addr, getChecker(), false)
} else {
sshClient, err = ssh.NewSSHClient("core", addr, getChecker(), false)
}
if err != nil {
return err, -1
}
defer sshClient.Close()
return ssh.Execute(sshClient, cmd)
}