views:

137

answers:

3
+3  Q: 

C++ add linux user

Hello,

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!

+3  A: 

Adding a user is a bit too high-level for there to be a system call for it. As far as I'm aware, there aren't any widely used libraries for this either. Your best bet will probably be to use the system call to invoke the useradd program with appropriate options.

Tyler McHenry
Few things:* Don't use system() unless you're very sure that things you pass won't be interpreted as special characters by the shell.* useradd isn't particularly portable (and on some systems you may not be able to create a "normal" user, e.g. one where users are in LDAP/NIS/AD/etc.In general, for one-off user creation I'd use a shell script.
tc.
+3  A: 

You might try using the libuser library.

One of the applications that are distributed with libuser is luseradd, a program that appears to be a cross-platform useradd utility. At its core, luseradd uses libuser's lu_user_add function to physically create the user.

See the docs/html folder in the source distribution for documentation.

Daniel Trebbien
+3  A: 

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.

indiv