/
shell.go
99 lines (84 loc) · 2.07 KB
/
shell.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
96
97
98
99
// Copyright (2012) Sandia Corporation.
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
package main
import (
"bytes"
"minicli"
log "minilog"
"os/exec"
)
var shellCLIHandlers = []minicli.Handler{
{ // shell
HelpShort: "execute a command",
HelpLong: `
Execute a command under the credentials of the running user.
Commands run until they complete or error, so take care not to execute a command
that does not return.`,
Patterns: []string{
"shell <command>...",
},
Call: wrapSimpleCLI(func(ns *Namespace, c *minicli.Command, resp *minicli.Response) error {
return cliShell(c, resp, false)
}),
},
{ // background
HelpShort: "execute a command in the background",
HelpLong: `
Execute a command under the credentials of the running user.
Commands run in the background and control returns immediately. Any output is
logged at the "info" level.`,
Patterns: []string{
"background <command>...",
},
Call: wrapSimpleCLI(func(ns *Namespace, c *minicli.Command, resp *minicli.Response) error {
return cliShell(c, resp, true)
}),
},
}
func cliShell(c *minicli.Command, resp *minicli.Response, background bool) error {
var sOut bytes.Buffer
var sErr bytes.Buffer
p, err := exec.LookPath(c.ListArgs["command"][0])
if err != nil {
return err
}
args := []string{p}
if len(c.ListArgs["command"]) > 1 {
args = append(args, c.ListArgs["command"][1:]...)
}
cmd := &exec.Cmd{
Path: p,
Args: args,
Env: nil,
Dir: "",
Stdout: &sOut,
Stderr: &sErr,
}
log.Info("starting: %v", args)
if err := cmd.Start(); err != nil {
return err
}
if background {
go func() {
if err := cmd.Wait(); err != nil {
log.Error(err.Error())
return
}
log.Info("command %v exited", args)
if out := sOut.String(); out != "" {
log.Info(out)
}
if err := sErr.String(); err != "" {
log.Info(err)
}
}()
return nil
}
if err = cmd.Wait(); err != nil {
return err
}
resp.Response = sOut.String()
resp.Error = sErr.String()
return nil
}