使用os.exec执行'su'返回错误

As I understand it Go's exec function executes the command directly with the kernel, rather than creating a local a terminal session or something like that. Unfortunately, I need to use the su command in order to run a script, which involves running su then piping the root password in via stdin.

Yes I have to use su (business use case on devices with sudo disabled), and I also do need to be able to pipe the password in.

So far the code I have is as follows

rootRun := exec.Command("su", "-c", "whoami")

rootRun.Stderr = os.Stdout
rootRun.Stdout = os.Stdout

err = rootRun.Run()
check(err)

and the error is

su: must be run from a terminal
panic: exit status 1

The only way I can think to do this would be to somehow emulate a terminal on the machine with go (I dont know what packages could be used, please let me know if you know of one) or create some kind of local ssh connection that gives me a pty session to work with, but thats not great as the devices will sometimes have ssh disabled. Hopefully there is another way around this, please let me know.

Try running it so that it's connected to a pseudo TTY.

github.com/kr/pty and other packages may help with this.


I must recap what others have written in their respective comments that this practice is utterly and irreversively broken.