We have a Go automation script which creates Linux users, the script runs under a different user, called scriptuser
but this script uses exec.Command
to create new users. The problem is we want to add the user scriptuser
inside the newly created user’s group, so that the scriptuser
can read/write into the user’s home directory whenever it needs to make new changes. We are able to add the scriptuser
to the newly created user’s group without any issues but the script user’s groups are not being changed unless we logout and log back in from the shell. How can we achieve this without logging out and logging back in.
NOTE: scriptuser
has sudo privileges
The below code is run with the user scriptuser
Example code
func setupUser(username string) {
cmd,err := exec.Command("sudo", "useradd","-m",username)
cmd.Run()
if err!=nil {
// handle error
}
cmd,err exec.Command("sudo","chmod","g+w","/home/"+username) // provide write perms at a group level
cmd, err = exec.Command("sudo", "adduser", "scriptuser", username) // add scriptuser to the newly created user's group
out, err = cmd.Output()
if err != nil {
log.Fatal(err)
}
os.Create("/home/"+username + "/sample.txt") // get a permission denied error even though I have added `scriptuser` as part of the new user's group, that is because scriptuser's groups have not been reloaded yet.
}
I tried adding exec.Command(“newgrp”, “<new_user_group>”) and exec.Command(“newgrp”) in sequence but it did not reload the groups.
1