C ++ add linux user

How can I add a user / group to Linux using C ++, is there a library I can call? I donโ€™t 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!

+7
c ++ c linux
source share
3 answers

I noticed that most of the basic utilities that add and change users do it directly, often in different ways. Functions that you can use to modify passwd and shadow files are displayed in <pwd.h> and <sys/types.h> , and they are part of glibc .

fgetpwent , getpwnam , getpw , getpwent_r , putpwent , setpwent

We can see how busybox (via TinyLogin ) does this as an example. In busybox/loginutils/adduser.c they put the user in the passwd file, creating a passwd structure, and then call putpwent . To add a user password to a shadow file, they simply call fprintf and write the line directly.

For user authentication, a modern way is Linux-PAM . But as for adding users, you can see in pam_unix_passwd.c that they call unix_update_db () , which calls various functions in libpwdb that you must add as a dependency to your project if you use it.

As I said, itโ€™s my fault that I wrote a couple of utilities for analyzing passwd and shadow databases and changing them directly. It worked fine, but it was on an embedded system where I could have full control of everything. I did not have to worry about things like race conditions with other programs that change passwd db.

If you need to add a group, then it also applies to the database .

+5
source share

You can try using the libuser library.

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

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

+4
source share

Adding a user is too high-level to have a system call for him. As far as I know, there are no widespread libraries for this. It is best to use the system call to call useradd with the appropriate parameters.

+3
source share

All Articles