Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Need feature for running ExecuteScript as the root user #87

Open
afbjorklund opened this issue May 12, 2024 · 0 comments
Open

Need feature for running ExecuteScript as the root user #87

afbjorklund opened this issue May 12, 2024 · 0 comments

Comments

@afbjorklund
Copy link
Member

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant