I need to programmely switch the current user to another,then the followed code should be executed in the environment(such as path,authority..) of another user.
I’ve find the ‘chroot()’,’setuid()’ may be associated with my case, but these functions need the root authority, I don’t have root authority, but I have the password of the second user. what should I do?
I have tried shell “su – ” can switch current user, can this command help me in my C++ code?
Don’t laugh at me if my question is very stupid, I’m a true freshman on linux. 🙂
Thanks!
If your primary requirement is to authenticate, then try
man pam. There are also some libraries allowing to auth over LDAP. Unfortunately I have no personal experience implementing neither.Otherwise, recreating complete user environment is unreliable and error prone. Imaging a typo or endless loop but in user’s ~/.profile.
I haven’t done that for some time, but I would also have tried to dig in direction of “su”, figuring out user shell (from /etc/passwd) and trying to exec() it as if it was a login shell (with “-“). But after that you would need somehow to communicate a command for execution to it and that’s a problem: shells run differently in batch more and in interactive mode. As a possible hack, expect (
man expect) comes to mind, but it is still IMO too unreliable.I have in past used
sshunderexpect(to input the password), but it was breaking on customized user profiles every other time. Withexpect, to send a command, one has to recognize somehow that shell has finished initialization (execution of profile and rc files). But since many people customize the shell prompt and their profile/rc files print extra info, it was quite often thatexpectwas recognizing shell prompt too soon.BTW, depending on number of users, one can try a setup where users manually start the server under their own account. The server would have access only to the information which is only accessible to the user.