Manage local user accounts

Assuming node is running as root, how do I:

  • Add a new local (OS) user account and get its uid?
  • Delete an account by name?

The accounts will be used for daemon processes, so they needn't be full-fledged user accounts.

Doing this on Linux is priority one, doing it on OS X would be nice, and super bonus for supporting Windows.

On Linux, I suppose you could just spawn useradd, but how would you determine the new user's uid? Would it be better (or worse) to modify /etc/passwd and friends directly?

On Windows, it looks like NetUserAdd is the right place to look; has someone already written an addon to call it?

For Linux, once you've created the account with useradd, you could call getent passwd <username> to see all the main relevant account details, including, in the 3rd field, the uid.

Example:

# useradd -c "Jamie Carter" jamiec

# getent passwd jamiec

yields:

jamiec:x:2722:500:Jamie Carter:/home/jamiec:/bin/false

To grab the uid in a one liner, you could combine the cut command to grab the 3rd field while treating : as the delimiter:

$ getent passwd jamiec | cut -d: -f 3

2722

Generally it's much safer and easier not to manipulate /etc/passwd and friends directly. Most of what you would need to do is likely already in a system command somewhere. For example, userdel <username> will delete an account by name from /etc/passwd, but also takes care of removing the user from /etc/groups so you don't have orphaned information left there. (You would have to deal with this yourself if you wrote your own user-deleter.)

This is a big & broad question (MacOS, Windows, Linux all together), but to create a new user from the command line on the Macintosh is not trivial and would require you to be authenticated as root / admin.