开发者

Create new user programmatically [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How to开发者_如何学Go create a linux user using C/C++?

Is there any way to create new user from c program in Linux?


It's a fairly complicated process to do everything right. The easiest way for you would be to simply run the useradd program, either using system() or fork/exec . Otherwise, if you really, really need to do it in your own code, get the source for useradd and study it. See this question for info about finding the useradd source.


A user in most Linux systems is not something the kernel is aware of as such. For most systems, it's probably enough to edit the password file (/etc/passwd) accordingly. Of course, you often have to be root in order to be allowed to change the password file.

See this page for more on how to add a user. You can of course write a C program that either replicates the steps taken by the useradd command, or calls it directly.


Yes, the adduser or useradd command found on most systems is a C program that does it.

Creating a user is typically just a matter of adding an entry to /etc/passwd and related files, creating a home directory, and copying some files from /etc/skel into the home directory. Look at the source code of adduser or useradd for details.


I came up with the following slightly viable resource:

http://tldp.org/HOWTO/Shadow-Password-HOWTO-8.html

On howto integrate shadow support in your program. Mind you, this presumes static linkage with the passwd/shadow libs. This places the (IMHO enormous) burden of providing immediate security updates once a security issue has been fixed in the upstream code (because the statically linked code will have been baked into your application, including the security flows/bugs that were fixed upstream).


There are two ways.

First you can create the user by changing the user database. In the most simple case this is /etc/passwd and /etc/shadow. If you want to create an own group for the user, which is the normal case on modern Linux systems, you have to alter /etc/group and /etc/gshadow. But you can not be sure that this works, because the system could take the users from a NIS or LDAP domain. In that case the user has to be created on the NIS or LDAP server.

The second way is to execute the operating system command, which does the job. This is useradd. There are various way how to do it. The most simple is to call system

system("useradd newguy");

This involves the execution of a shell. The more advanced way is to do a fork with an execve() on the useradd binary. But the result is the same.

For examples see man pages man system(3), man fork(3) and man execve(3).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜