Skip to content

Need feature for running ExecuteScript as the root user #87

Open
@afbjorklund

Description

@afbjorklund

Currently I just made a copy/paste version, that was called sudoExecuteScript

It would be nice if this feature was available through the regular functions?

@@ -1,8 +1,8 @@
-// ExecuteScript executes the given script on the remote host via stdin.
+// sudoExecuteScript executes the given script (as root) on the remote host via stdin.
 // Returns stdout and stderr.
 //
 // scriptName is used only for readability of error strings.
-func ExecuteScript(host string, port int, c *SSHConfig, script, scriptName string) (string, string, error) {
+func sudoExecuteScript(host string, port int, c *ssh.SSHConfig, script, scriptName string) (stdout, stderr string, err error) {
 	if c == nil {
 		return "", "", errors.New("got nil SSHConfig")
 	}
@@ -15,15 +15,15 @@
 	if port != 0 {
 		sshArgs = append(sshArgs, "-p", strconv.Itoa(port))
 	}
-	sshArgs = append(sshArgs, host, "--", interpreter)
+	sshArgs = append(sshArgs, host, "--", "sudo", interpreter)
 	sshCmd := exec.Command(sshBinary, sshArgs...)
 	sshCmd.Stdin = strings.NewReader(script)
-	var stderr bytes.Buffer
-	sshCmd.Stderr = &stderr
+	var buf bytes.Buffer
+	sshCmd.Stderr = &buf
 	logrus.Debugf("executing ssh for script %q: %s %v", scriptName, sshCmd.Path, sshCmd.Args)
 	out, err := sshCmd.Output()
 	if err != nil {
-		return string(out), stderr.String(), fmt.Errorf("failed to execute script %q: stdout=%q, stderr=%q: %w", scriptName, string(out), stderr.String(), err)
+		return string(out), buf.String(), fmt.Errorf("failed to execute script %q: stdout=%q, stderr=%q: %w", scriptName, string(out), buf.String(), err)
 	}
-	return string(out), stderr.String(), nil
+	return string(out), buf.String(), nil
 }

(renamed the "stderr" variable due to go-critic, feel free to ignore)

unnamedResult: consider giving a name to these results (gocritic)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions