Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exec as another user

Tags:

go

exec

How to execute shell command with another user in GO, and get output from it ?

I tried:

cmd :=exec.Command("sudo","su",username, "-c",command)
stdout, err := cmd.StdoutPipe()
CheckErr(err)
cmd.Run()

there is no output. anyone know how to do this?

like image 984
Rizky Ramadhan Avatar asked Nov 22 '25 08:11

Rizky Ramadhan


1 Answers

You need to check the output of running the cmd.Run and also get your output using stdout is simpler than using the pipe.

cmd :=exec.Command("sudo","su",username, "-c",command)
cmd.Stderr = os.Stdout
cmd.Stdout = os.Stdout

err := cmd.Run()
CheckErr(err)

That should give you visibility of the error so you can find out what is occuring that prevents the sudo.

like image 88
miltonb Avatar answered Nov 24 '25 22:11

miltonb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!