Search code examples
goexecsudo

Is it possible to run a sudo command in go without running the program itsself as sudo


The program runs multiple commands that require sudo privileges (such as sudo dnf update). Since the program should be installed using the go install command, it can't be run as sudo its self without configuration done by the user (afaik).

The program doesn't show the output to the user to keep the output clean. To show that a process is running, it uses a spinner from the spinner library.

Is it possible to do any of these things?

  • Obtain sudo privileges from within the program
  • Make the program runnable as sudo, even when installed using go install
  • Show the output of the sudo command (including the password request) without it being overwritten by the spinner

Here is a shortened version of what I would like my code to do:

package main

import (
    "fmt"
    "os"
    "os/exec"
    "time"

    "github.com/briandowns/spinner"
)

func main() {
    // Spinner to show that it's running
    s := spinner.New(spinner.CharSets[14], time.Millisecond*100)
    s.Start()

    // Somehow execute this with sudo
    _, err := exec.Command(os.Getenv("SHELL"), "-c", "dnf update -y").Output()

    // Stop the spinner and handle any error
    if err != nil {
        fmt.Printf("Err: %s", err)
        os.Exit(1)
    }
    s.Stop()

    // Finish
    fmt.Println("Success")
}

Solution

  • _, err := exec.Command(os.Getenv("SHELL"), "-c", "sudo dnf update -y").Output()

    In this exapmle, with adding sudo before the command that you want run as sudo, and after running the program, will ask password for sudo, If you apply this to your example code you can't see password request message, because the spinner graphics will overwrite it, but if you try this without spinner graphics you can see it. Even you don't see the message, if you type your correct password and press enter your commands will work as sudo. With this, you don't need run your application as sudo. I have ran similar commands with using this and they have worked.