Executing bash command with sudo privileges

Is it possible to execute a bash command including sudo with exec.Command? For example the code below executes fine for Execute(“ls /”), but hangs during Execute(“sudo mkdir /test”).

What I think I would like is that the dialog that asks for password is being opened when it includes sudo.

I am testing this on Manjaro Linux…

func main() {
	//fmt.Println(Execute("ls /"))
	fmt.Println(Execute("sudo mkdir /test"))
}

func Execute(command string) string {
	cmd := exec.Command("bash", "-c", command)
	// Make sure that a new separate process is created
	// that won't be killed when this process exits
	cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}

	output, err := cmd.Output()
	if err!=nil {
		fmt.Println(err.Error())
	}

	return string(output)
}

I am asking because I am writing a program, that starts applications and scripts, for me. I know that such applications already exists, but I wanted to write it myself. For example, when I type gimp in my starter program, I want it to start Gimp for me. And when I type fstab, I want it to run sudo xed /etc/fstab or sudo nano /etc/fstab. Running xed /etc/fstab works fine of course, but then I can’t edit the file.

Well, here is one acceptable solution. It opens a gnome-terminal and executes the command sudo nano /etc/fstab and therefor immediately asks you for your sudo password, and then you can edit the file. It is a little bit unfortunate that you can’t see the command that it wants the sudo password for though. But hey, I trust myself…most of the times…

package main

import (
	"fmt"
	"os/exec"
	"syscall"
)

func main() {
	fmt.Println(Execute("gnome-terminal -x sudo nano /etc/fstab"))
}

func Execute(command string) string {
	commands := append([]string{"-c"}, command)
	cmd := exec.Command("bash", commands...)
	// Make sure that a new separate process is created
	// that won't be killed when this process exits
	cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}

	output, err := cmd.Output()
	if err!=nil {
		fmt.Println(err.Error())
	}

	return string(output)
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.