// execCmd executes the specified command, returning the STDOUT content.
// If command exits with error status, the output is captured into the returned error.
327132
func execCmd(arg0 string, args ...string) ([]byte, error) {
	if wlog.LogLevel() == wlog.DEBUG {
		quoted := make([]string, 0, len(args))
		for _, arg := range args {
			quoted = append(quoted, fmt.Sprintf("%q", arg))
		}
		log.Printf("D! [inputs.snmp] Executing %q %s", arg0, strings.Join(quoted, " "))
	}

	out, err := execCommand(arg0, args...).Output()
	if err != nil {
		if err, ok := err.(*exec.ExitError); ok {
			return nil, NestedError{
				Err:       err,
				NestedErr: fmt.Errorf("%s", bytes.TrimRight(err.Stderr, "\r\n")),
			}
		}
		return nil, err
	}
	return out, nil
}
1161635
func execGitCmd(ctx context.Context, args []string, config gitCmdConfig) error {
	c := exec.CommandContext(ctx, "git", args...)

	if config.dir != "" {
		c.Dir = config.dir
	}
	c.Env = append(env(), config.env...)
	c.Stdout = ioutil.Discard
	if config.out != nil {
		c.Stdout = config.out
	}
	errOut := &bytes.Buffer{}
	c.Stderr = errOut

	traceStdout := &bytes.Buffer{}
	traceStderr := &bytes.Buffer{}
	if trace {
		c.Stdout = io.MultiWriter(c.Stdout, traceStdout)
		c.Stderr = io.MultiWriter(c.Stderr, traceStderr)
	}

	err := c.Run()
	if err != nil {
		msg := findErrorMessage(errOut)
		if msg != "" {
			err = errors.New(msg)
		}
	}

	if trace {
		if traceCommand := traceGitCommand(args, config, traceStdout.String(), traceStderr.String()); traceCommand != "" {
			println(traceCommand)
		}
	}

	if ctx.Err() == context.DeadlineExceeded {
		return errors.Wrap(ctx.Err(), fmt.Sprintf("running git command: %s %v", "git", args))
	} else if ctx.Err() == context.Canceled {
		return errors.Wrap(ctx.Err(), fmt.Sprintf("context was unexpectedly cancelled when running git command: %s %v", "git", args))
	}
	return err
}
1052860
func ExecScript(script string) (*exec.Cmd, error) {
	var shell, flag string
	if runtime.GOOS == "windows" {
		shell = "cmd"
		flag = "/C"
	} else {
		shell = "/bin/sh"
		flag = "-c"
	}
	if other := os.Getenv("SHELL"); other != "" {
		shell = other
	}
	cmd := exec.Command(shell, flag, script)
	return cmd, nil
}
1271715
func Command(args ...string) *exec.Cmd {
	cmd := exec.Command(Self())
	cmd.Args = args
	return cmd
}
815286
func (c *Command) Exec(f interface{}, args ...interface{}) Return {
	return c.ExecTimeout(c.Timeout, f, args...)
}
649007
func (c *Client) Exec(cmd string) ([]byte, error) {
	session, err := c.SSHClient.NewSession()
	if err != nil {
		return nil, err
	}
	defer session.Close()

	return session.CombinedOutput(cmd)
}
1131183
func ExecCmdWithStdStreams(stdin io.Reader, stdout, stderr io.Writer, name string, args ...string) error {
	cmd := exec.Command(name, args...)
	cmd.Stdin = stdin
	cmd.Stdout = stdout
	cmd.Stderr = stderr
	if v, found := os.LookupEnv("XDG_RUNTIME_DIR"); found {
		cmd.Env = append(cmd.Env, fmt.Sprintf("XDG_RUNTIME_DIR=%s", v))
	}

	err := cmd.Run()
	if err != nil {
		return fmt.Errorf("`%v %v` failed: %v", name, strings.Join(args, " "), err)
	}

	return nil
}
1326221
func (c *Client) Exec(cmd string) ([]string, error) {
	return c.ExecCmd(NewCmd(cmd))
}
564247
func execWithFunc(name string, args []string, env []string, execCmd execCmd, timeout time.Duration, log Log) (Result, error) {
	var result Result
	log.Debugf("Execute: %s %s", name, args)
	if name == "" {
		return result, fmt.Errorf("No command")
	}
	if timeout < 0 {
		return result, fmt.Errorf("Invalid timeout: %s", timeout)
	}
	cmd := execCmd(name, args...)
	if cmd == nil {
		return result, fmt.Errorf("No command")
	}
	cmd.Stdout = &result.Stdout
	cmd.Stderr = &result.Stderr
	if env != nil {
		cmd.Env = env
	}
	err := cmd.Start()
	if err != nil {
		return result, err
	}
	result.Process = cmd.Process
	doneCh := make(chan error)
	go func() {
		doneCh <- cmd.Wait()
		close(doneCh)
	}()
	// Wait for the command to finish or time out
	select {
	case cmdErr := <-doneCh:
		log.Debugf("Executed %s %s", name, args)
		return result, cmdErr
	case <-time.After(timeout):
		// Timed out
		log.Warningf("Process timed out")
	}
	// If no process, nothing to kill
	if cmd.Process == nil {
		return result, fmt.Errorf("No process")
	}

	// Signal the process to terminate gracefully
	// Wait a second or timeout for termination, whichever less
	termWait := time.Second
	if timeout < termWait {
		termWait = timeout
	}
	log.Warningf("Command timed out, terminating (will wait %s before killing)", termWait)
	err = cmd.Process.Signal(syscall.SIGTERM)
	if err != nil {
		log.Warningf("Error sending terminate: %s", err)
	}
	select {
	case <-doneCh:
		log.Warningf("Terminated")
	case <-time.After(termWait):
		// Bring out the big guns
		log.Warningf("Command failed to terminate, killing")
		if err := cmd.Process.Kill(); err != nil {
			log.Warningf("Error trying to kill process: %s", err)
		} else {
			log.Warningf("Killed process")
		}
	}
	return result, fmt.Errorf("Timed out")
}
660205
func (cmd *Cmd) Exec() error {
	verboseLog(cmd)

	binary, err := exec.LookPath(cmd.Name)
	if err != nil {
		return &exec.Error{
			Name: cmd.Name,
			Err:  fmt.Errorf("command not found"),
		}
	}

	args := []string{binary}
	args = append(args, cmd.Args...)

	return syscall.Exec(binary, args, os.Environ())
}
1211744
func (p *Init) exec(ctx context.Context, path string, r *ExecConfig) (proc.Process, error) {
	// process exec request
	var spec specs.Process
	if err := json.Unmarshal(r.Spec.Value, &spec); err != nil {
		return nil, err
	}
	spec.Terminal = r.Terminal

	e := &execProcess{
		id:     r.ID,
		path:   path,
		parent: p,
		spec:   spec,
		stdio: proc.Stdio{
			Stdin:    r.Stdin,
			Stdout:   r.Stdout,
			Stderr:   r.Stderr,
			Terminal: r.Terminal,
		},
		waitBlock: make(chan struct{}),
		pid:       &safePid{},
	}
	e.execState = &execCreatedState{p: e}
	return e, nil
}
1136198
func (t *Tool) Exec(path string, stop <-chan bool) (response Response) {
	if t.dir {
		if filepath.Ext(path) != "" {
			path = filepath.Dir(path)
		}
		// check if there is at least one go file
		matched := false
		files, _ := ioutil.ReadDir(path)
		for _, f := range files {
			matched, _ = filepath.Match("*.go", f.Name())
			if matched {
				break
			}
		}
		if !matched {
			return
		}
	} else if !strings.HasSuffix(path, ".go") {
		return
	}
	args := t.Args
	if strings.HasSuffix(path, ".go") {
		args = append(args, path)
		path = filepath.Dir(path)
	}
	if s := ext(path); s == "" || s == "go" {
		if t.parent.parent.Settings.Recovery.Tools {
			log.Println("Tool:", t.name, path, args)
		}
		var out, stderr bytes.Buffer
		done := make(chan error)
		args = append(t.cmd, args...)
		cmd := exec.Command(args[0], args[1:]...)
		if t.Dir != "" {
			cmd.Dir, _ = filepath.Abs(t.Dir)
		} else {
			cmd.Dir = path
		}
		cmd.Stdout = &out
		cmd.Stderr = &stderr
		// Start command
		err := cmd.Start()
		if err != nil {
			response.Name = t.name
			response.Err = err
			return
		}
		go func() { done <- cmd.Wait() }()
		// Wait a result
		select {
		case <-stop:
			// Stop running command
			cmd.Process.Kill()
		case err := <-done:
			// Command completed
			response.Name = t.name
			if err != nil {
				response.Err = errors.New(stderr.String() + out.String() + err.Error())
			} else {
				if t.Output {
					response.Out = out.String()
				}
			}
		}
	}
	return
}
920105
func (mc *mysqlConn) exec(query string) error {
	// Send command
	if err := mc.writeCommandPacketStr(comQuery, query); err != nil {
		return mc.markBadConn(err)
	}

	// Read Result
	resLen, err := mc.readResultSetHeaderPacket()
	if err != nil {
		return err
	}

	if resLen > 0 {
		// columns
		if err := mc.readUntilEOF(); err != nil {
			return err
		}

		// rows
		if err := mc.readUntilEOF(); err != nil {
			return err
		}
	}

	return mc.discardResults()
}
600991
func runCommand(cmd string) error {
	log.Debug("Running " + cmd)
	var c *exec.Cmd
	if runtime.GOOS == "windows" {
		c = exec.Command("cmd", "/C", cmd)
	} else {
		c = exec.Command("/bin/sh", "-c", cmd)
	}

	output, err := c.CombinedOutput()
	if err != nil {
		log.Error(fmt.Sprintf("%q", string(output)))
		return err
	}
	log.Debug(fmt.Sprintf("%q", string(output)))
	return nil
}
799175
func (c *Client) ExecuteCommand(cmd string) (string, error) {
	err := c.VerifyClient()
	if err != nil {
		return "", err
	}

	// Don't allocate something we may not need, e.g. if we can't build a client
	var b bytes.Buffer

	// Each ClientConn can support multiple interactive sessions,
	// represented by a Session.
	s, err := c.client.NewSession()
	if err != nil {
		return "", err
	}

	// Once a Session is created, you can execute a single command on
	// the remote side using the Run method.
	s.Stdout = &b

	err = s.Run(cmd)
	if err != nil {
		return "", err
	}

	return b.String(), nil
}
1369891
func (t *Transaction) Exec() ([]*Reply, error) {
	if err := t.conn.SendCommand("EXEC"); err != nil {
		return nil, err
	}
	rp, err := t.conn.RecvReply()
	if err != nil {
		return nil, err
	}
	return rp.MultiValue()
}
710803
func (ftp *FTP) cmd(expects string, command string, args ...interface{}) (line string, err error) {
	if err = ftp.send(command, args...); err != nil {
		return
	}

	if line, err = ftp.receive(); err != nil {
		return
	}

	if !strings.HasPrefix(line, expects) {
		err = errors.New(line)
		return
	}

	return
}