Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ add linux user

Whats the best way to add a user/group in linux using C++ is there a library I can call on? I dont want to start doing things like:

fopen("/etc/passwd", "a");
 fprintf(tmp, "%s:x:%d:1:%s:/%s/%s:/bin/ksh\n", username, usernumber, commentfield, userdir, username);
 fclose(tmp);

fopen("/etc/shadow", "a");
 fprintf(stmp, "%s:*LK*:::::::\n", username);
 fclose(stmp);

Thanks!

like image 440
James Moore Avatar asked Jun 21 '10 16:06

James Moore


People also ask

How do I add a user to my home directory in Linux?

Creating a user with a custom home directoryBy default, useradd will create the user's home directory under “/home”. To specify the home directory in a different location, use the flag “-d”. Note that the directory must exist beforehand. As always, use passwd to assign a login password for the new user.

How do I add a user to a group in Linux?

You can add a user to a group in Linux using the usermod command. To add a user to a group, specify the -a -G flags. These should be followed by the name of the group to which you want to add a user and the user's username.


1 Answers

I've noticed that most major utilities that add and change users do so directly, often in different ways. The functions you can use to modify the passwd and shadow files are exposed in <pwd.h> and in <sys/types.h>, and they're part of glibc.

fgetpwent, getpwnam, getpw, getpwent_r, putpwent, setpwent

We can look into how busybox (via TinyLogin) does it, as an example. In busybox/loginutils/adduser.c, they put a user in the passwd file by building the passwd structure and then call putpwent. For adding the user's password in the shadow file, they simply call fprintf and write the string directly.

For authenticating users the modern way, there's Linux-PAM. But as far as adding users, you can see in pam_unix_passwd.c that they call unix_update_db(), which calls various functions in libpwdb, which you'd have to add as a dependency to your project if you use it.

That being said, I'm guilty of having written a couple utilities to parse the passwd and shadow databases and modify them directly. It worked fine, but this was on an embedded system where I could tightly control everything. I didn't have to worry about things like race conditions with other programs modifying the passwd db.

If you need to add a group, same goes for the group database.

like image 181
indiv Avatar answered Sep 23 '22 02:09

indiv