In Go, the os/exec package provides a way to run external commands from a program. However, by default, commands are run with the same user privileges as the program itself.
To run commands with a different user's privileges without resorting to the su or bash commands, you can use syscall.Credential. Here's an example:
import ( "os/exec" "syscall" ) func runAsUser(command string, args []string, username string) error { // Look up the target user's UID and GID u, err := user.Lookup(username) if err != nil { return err } uid, err := strconv.Atoi(u.Uid) if err != nil { return err } gid, err := strconv.Atoi(u.Gid) if err != nil { return err } // Create a command and set its SysProcAttr to run as the specified user cmd := exec.Command(command, args...) cmd.SysProcAttr = &syscall.SysProcAttr{ Credential: &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid)}, } // Run the command return cmd.Run() }
While not recommended due to potential security risks, you can also use syscall.Setuid to change the effective user ID of the current process.
import ( "os" "syscall" ) func setUid(username string) error { // Look up the target user's UID u, err := user.Lookup(username) if err != nil { return err } uid, err := strconv.Atoi(u.Uid) if err != nil { return err } // Set the effective user ID to the specified user return syscall.Setuid(uid) }
Note:
The above is the detailed content of How to Run External Commands as Another User in Go Without Using su or bash?. For more information, please follow other related articles on the PHP Chinese website!