How to: Add a user from the OS X command line, works with Leopard!

Oct 29, 2007 - 53 Comments

Adding a user is something easily accomplished using the built in GUI tools that ship with OS X, however any power user can appreciate the possible efficiency gained from using the command line. So in the spirit of efficiency here are the steps necessary to add a user to your Mac OS X system all with our good friend, Terminal.app.

These commands need to be run as either the root user or with the “sudo” command. For more information on the sudo command see the sudo man page.

Create a new entry in the local (/) domain under the category /users.
dscl / -create /Users/toddharris

Create and set the shell property to bash.
dscl / -create /Users/toddharris UserShell /bin/bash

Create and set the user’s full name.
dscl / -create /Users/toddharris RealName "Dr. Todd Harris"

Create and set the user’s ID.
dscl / -create /Users/toddharris UniqueID 503

Create and set the user’s group ID property.
dscl / -create /Users/toddharris PrimaryGroupID 1000

Create and set the user home directory.
dscl / -create /Users/toddharris NFSHomeDirectory /Local/Users/toddharris

Set the password.
dscl / -passwd /Users/toddharris PASSWORD

or

passwd toddharris

If you would like Dr. Harris to be able to perform administrative functions:
dscl / -append /Groups/admin GroupMembership toddharris

Enjoy this tip? Subscribe to the OSXDaily newsletter to get more of our great Apple tips, tricks, and important news delivered to your inbox! Enter your email address below:

Related articles:

Posted by: Bill Ellis in Command Line, How to, Leopard, Mac OS X, Tips & Tricks

53 Comments

» Comments RSS Feed

  1. Zamgar says:

    sweet thats really useful

  2. NB says:

    Unable to get it to work? Invalid Path (/)

  3. david koff says:

    i love this. i’d created a script a while back for remotely creating a HIDDEN user called “ard” on 10.4.x systems, turning all ARD incoming functions on for that user and editing the login window and fast user-switching windows to NOT mention this user. and now, that script, below, will not work on on leopard. so i’m glad to have this listed here instead!

    david

    niutil -create / /users/ard
    niutil -appendprop / /groups/admin GroupMembership ard
    niutil -appendprop / /users/ard “shell” “/bin/bash”
    niutil -appendprop / /users/ard “_writers_hint” ard
    niutil -appendprop / /users/ard “NFSHomeDirectory” “/var/root”
    niutil -appendprop / /users/ard “gid” “405″
    niutil -appendprop / /users/ard “uid” “405″
    niutil -appendprop / /users/ard “authentication_authority” “;ShadowHash;”
    niutil -appendprop / /users/ard “_writers_realname” ard
    niutil -appendprop / /users/ard “picture” “/Library/User Pictures/Nature/Zen.tif”
    niutil -appendprop / /users/ard “passwd” “whatever-your-password-is”
    niutil -appendprop / /users/ard “realname” “ARD”
    niutil -appendprop / /users/ard “hint” “whatever-your-password-is”
    sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -access -on -users ard -privs -all -restart -agent -menu
    sudo defaults write /Library/Preferences/com.apple.loginwindow \HiddenUsersList -array-add ard
    sudo defaults write /Library/Preferences/com.apple.loginwindow SHOWOTHERUSERS_MANAGED -bool false

  4. ilia says:

    doesn’t work for me.
    Data source (/) is not valid.

  5. Pim says:

    It changed for leopard. Use “dscl localhost -whatever /Local/Users”, replacing every instance of a solitary “/” with “localhost” and changing /Users to /Local/users. Hope that helps.

  6. kl says:

    on Leopard I’ve had to use:
    > sudo dscl localhost -create /Local/Default/Users/username

  7. Ivan says:

    On Leopard 10.5 final, substituting “.” for the “/” works. I needed to perform software updates and other admin functions on a Mac with Leopard that I didn’t have the admin password for. Adapting the above steps allowed me to do so (thanks!). What I did:

    [boot into single-user mode (hold down cmd-S during early startup)]
    /sbin/fsck -fy (to verify integrity of the filesystem)
    /sbin/mount -uw / (to be able to make changes to the disk)
    launchctl load /System/Library/LaunchDaemons/com.apple.DirectoryServices.plist (to be able to use dscl)
    dscl . -create /Users/testuser
    dscl . -create /Users/testuser UserShell /bin/bash
    dscl . -create /Users/testuser RealName “Test User”
    dscl . -create /Users/testuser UniqueID 502 (see notes below about this)
    dscl . -create /Users/testuser PrimaryGroupID 80 (I chose to make the user a member of the admin group)
    dscl . -create /Users/testuser NFSHomeDirectory /Users/testuser (note this is changed from above)
    dscl . -passwd /Users/testuser PASSWORD
    dscl . -append /Groups/admin GroupMembership testuser
    exit
    [restart after Mac OS X loads or login window appears]
    [log out if Mac OS X loads straight into a user rather than a login window]
    [log in as testuser]
    [update software, enable root user, do whatever you like]

    And then, when I’m ready to delete the user:
    [boot into single-user mode]
    /sbin/fsck -fy (to verify integrity of the filesystem)
    /sbin/mount -uw / (to be able to make changes to the disk)
    launchctl load /System/Library/LaunchDaemons/com.apple.DirectoryServices.plist (to be able to use dscl)
    dscl . -delete /Groups/admin GroupMembership testuser
    dscl . -delete /Users/testuser
    cd Users
    rm -rf testuser (warning: will delete any files in user home folder)
    exit
    [restart or shut down after Mac OS X loads]

    I chose the UniqueID (502) in a way consistent with the OS: the number 5xx where xx is one greater than the number of users ever created. To figure out the best available number, before issuing the dscl commands to create the user (but after the launchctl command), I typed:
    dsexport users.out /Local/Default dsRecTypeStandard:Users
    more users
    I then scanned the list of users to see any 5xx users and then chose the next highest one available. There was only one user on this system, so that meant 502. I then deleted the export user info file (rm users.out). (I imagine it probably doesn’t really matter what UniqueID you choose as long as it is unassigned, but I am not enough of a Unix guru to know for certain.)

  8. Rusty Myers says:

    Here’s my script using all of your guys suggestions. I’m going to be using it in my work environment at the university. It’s working on 10.5.1

    You need to run it as sudo like this:
    sudo ./makeuser.sh

    Copy this into the makeuser.sh file:

    #!/bin/bash

    echo “This script will create a user on Leopard”
    echo “”
    echo “Enter Fullname”
    read fullname
    echo “Enter username”
    read username
    echo “Enter usernumber”
    read usernumber
    echo “Enter Password”
    read password
    echo “Enter Password again”
    read password2
    echo “”
    if [ $password != $password2 ]
    then
    echo “Passwords do not match. Exiting…”
    exit 0
    else
    echo “Passwords Match!”
    fi

    echo “”
    echo “Full Name”$fullname
    echo “Username:”$username
    echo “UID:” $usernumber
    echo “Password:” $password
    echo “Are these details correct? Y or N?”
    read test
    echo “”
    if [ $test = Y -o $test = y ]
    then
    echo “Creating User “$username
    dscl . -create /Users/$username
    dscl . -create /Users/$username UserShell /bin/bash
    dscl . -create /Users/$username RealName $fullname
    dscl . -create /Users/$username UniqueID $usernumber
    dscl . -create /Users/$username PrimaryGroupID 80
    dscl . -create /Users/$username NFSHomeDirectory /Users/$username
    dscl . -passwd /Users/$username $password
    dscl . -append /Groups/admin GroupMembership $username
    echo “”
    echo $username” created! Enjoy!”
    else
    echo “Please run script again with correct information.”
    fi

    That should be it, enjoy! Email me with problems or suggestions. Thanks!

  9. Bertrand says:

    Reply to Rusty’s script.

    I am writing a similar script and have done pretty much all of the steps you have except I set functions so I can use the code over again easily. Also, in my script I am writing a function that compares the entered information against preexisting keys so that a user cannot get errors by creating users/UniqueIDs/PrimaryGroupIDs etc that already are assigned to other users I’m attempting to use dscl . -list but am having problems setting my variables (UniqueID etc) since the list command always wants to list the /Users as well as any other info you parse… any suggestions would be greatly appreciate.

    Thanks

  10. Bertrand says:

    this ended up working for me, if anybody has a more elegant way I’d love to learn. I’m just a humble padawan after all…

    function checkusername {
    local test=$(dscl . -list /Users | grep $SHORTNAME)
    if [ "$test" = "$SHORTNAME" ]; then
    echo the the username $SHORTNAME already exists
    exit
    else
    echo This would continue the script
    fi
    }

  11. Bertrand says:

    this ended up working for me, if anybody has a more elegant way I’d love to learn. I’m just a humble padawan after all…

    function checkusername {
    local test=$(dscl . -list /Users | grep $SHORTNAME)
    if [ "$test" = "$SHORTNAME" ]; then
    echo the the username $SHORTNAME already exists
    exit
    else
    echo This would continue the script
    fi
    }

  12. David says:

    Hi Bertrand,

    That’s a useful addition — could you integrate it into the script and show the whole thing? I’m feeling lazy this morning. Why define it as a function in the first place?

    What I’m really looking for is how to create a new user group from the command line ….

    Cheer

  13. David Liontooth says:

    How to change user and group numbers for an existing user to a non-existing group
    – Change user liontooth group staff to user liontooth UID 1000 group liontooth UID 1000
    – dscl . create /Groups/liontooth PrimaryGroupID 1000 GroupMembership liontooth
    – next log in and in System Prefs, Users, Advanced settings (right-click), set UID and GID to 1000
    – as root, cd /Users ; chown -R 1000:1000 liontooth
    – reboot — should all be working

  14. ichi says:

    all this did for me in 10.5.1 is make the Leopard style “Guest Account” into “Other…”

    run it again using NO and it comes back.

  15. ichi says:

    oops, i meant to add that this is what what i refer to:

    defaults write /Library/Preferences/com.apple.loginwindow Hide500Users -bool YES

    oops wrong website!

  16. RS says:

    I am having difficulty with David Koff’s solution. I keep getting errors with the niutil stating that I do not have enough arguments. Everything I have tried has failed. Can anyone help?

  17. RS says:

    Once I get this script working for creating the hidden user, how do I log in as him/her if their name does not appear anywhere.

  18. Mert says:

    i like to ask if it’s possible to change user in the script and continue the next steps with the changed user?
    In the script, I write : su – example and the program stops to process following codes

  19. jennj6 says:

    i odnt g et it????

  20. lucy says:

    OS X discovery every day!

  21. Audun Frøysaa says:

    Hello.
    When i log in as the new user created with dscl i get a message that the home folder can’t be found.

    sudo dscl . -create /Users/$userName
    sudo dscl . -create /Users/$userName UniqueID 555
    sudo dscl . -create /Users/$userName UserShell /bin/bash
    sudo dscl . -create /Users/$userName RealName “$forNavn $etterNavn”
    sudo dscl . -create /Users/$userName NFSHomeDirectory /Users/$userName
    sudo dscl . -create /Users/$userName PrimaryGroupID 20
    sudo dscl . -passwd /Users/$userName $passord

    sudo cp -R /System/Library/User\ Template/no.lproj /Users/$userName
    sudo chown -R $userName:staff /Users/$userName

    I have checked and the /Users/ exist and all the folders are created.
    What can be wrong?
    Thanks

  22. Jamie says:

    sudo dscl . -create /Users/$userName NFSHomeDirectory /Users/$userName

    change to

    sudo dscl . -create /Users/$userName home /Users/$userName

  23. [...] Gut – wie sollte es anders sein – dieser Weg fhrte bei mir nicht zum Ziel: Ich konnte im “Setup Assistent” meine Tastatur nicht mehr benutzen. Also mu es noch andere Wege geben – am einfachsten wre es ja, z.B. unter dem “Single User Mode” einen Benutzer mit Admin-Rechten zu erstellen, oder noch besser, den bestehenden Account wieder zur Admin-Gruppe hinzuzufgen. Ja, auch das ist mglich. [...]

  24. Rusty Myers says:

    I’m back!
    Thanks for your update Bertrand! I took what you did and added it, plus a little dash of checking userID’s too! Here is the new script. So far, I have tested it very successfully. Email me if you have any problems running it or any questions I might be able to help with…rustymyers@gmail.com

    I also added the ability to run it from single user mode, should you need to use it there. I bet there is an easier way to check if your in singleuser mode, but I decided just to ask.
    I added the dsexport command to check existing userID’s in the script so you don’t have to exit. It also cleans its self afterwards.
    I tried to make most of the checks functions.
    There is no need to create the user home folder in this script because the system creates it when you log into the account.
    You don’t see the user account in the login window if you use a list style, unless restarting. Change it to the username and password style to type it in and log in without restart. Once you log in the first time, you can change it back to list style, or you can just restart.

    I will be pushing it out to all my new computers to make user account creation easier, and so I don’t have to go through the setup assistant every time I get a new computer. Hope this helps someone else!

    #!/bin/bash

    #This script will create a user of your choice using your credentials. The user will not show up in the login window until a restart.

    #Function to check the current usernames against the new username.

    function checkusername {
    local testun=$(dscl . -list /Users | grep $userA)
    if [ "$testun" == "$userA" ];
    then
    echo “The username “$userA” already exists”
    exit
    else
    echo “Username is unique!”
    fi
    }

    #Function to check the current userID’s against the new userID.

    function checkuserid {
    local testuid=$(dscl . -list /Users UniqueID | grep “$userid” | awk ‘{print $2}’ )
    if [ "$testuid" == "$userid" ];
    then
    echo “The userid “$userid” already exists”
    exit
    else
    echo “UserID is unique!”
    fi
    }

    #Funtion to check that both passwords are the same.

    function chkpasswd {
    if [ $password != $password2 ]
    then
    echo “Passwords do not match or are blank. Passwords can’t be blank. Exiting…”
    exit 0
    else
    echo “Passwords Match!”
    fi
    }

    #Step 1, enter new credentials to create user with.

    echo “Enter Real Name”
    read realname
    echo “Enter Username”
    read userA
    checkusername
    echo “Enter Password”
    read password
    echo “Re-Enter Password”
    read password2
    chkpasswd

    #Check to see if your sure you want to use the entered credentials.

    echo “Use these creds?”
    echo “Real Name: “$realname
    echo “Username: “$userA
    echo “Password: “$password

    echo “Y or N:”
    read creds

    if [ $creds = y -o $creds = Y ];
    then
    echo “Let’s make a user named “$userA” with the password “$password
    echo “Are you in Single User Mode? (Default N)”
    read sum

    #Checks to see if your in single user mode. If you are, it loads the directory services plist.

    if [ $sum = y -o $sum = Y ];
    then
    echo “Loading Directory Services”
    launchctl load /System/Library/LaunchDaemons/com.apple.DirectoryServices.plist
    else
    echo “Skipping launchctl load”
    fi

    #Asks if you need to see all the userID’s already used.

    echo “Making user…”
    echo “Do you know what userID is availible? (Default Y)”
    read existuserid

    if [ $existuserid = n -o $existuserid = N ];
    then
    #Prints the existing user account records and inserts them to users.out.
    dsexport users.out /Local/Default dsRecTypeStandard:Users
    #Prints users.out to screen.
    tail -n 5 users.out
    echo “Find the next userID available.”
    #Removes users.out to clean up after printing to screen.
    rm users.out
    fi

    #Asks for the new userID. Checks if userID exists using checkuserid function.

    echo “OK, Enter new userID number:”
    read userid
    checkuserid

    #The meat of the script. These are the commands that create the user with your specified credentials.

    dscl . -create /Users/””$userA””
    dscl . -create /Users/””$userA”” UserShell /bin/bash
    dscl . -create /Users/””$userA”” RealName “$realname”
    dscl . -create /Users/””$userA”” UniqueID $userid
    dscl . -create /Users/””$userA”” PrimaryGroupID 80
    dscl . -create /Users/””$userA”” NFSHomeDirectory /Users/””$userA””
    dscl . -passwd /Users/””$userA”” $password
    dscl . -append /Groups/admin GroupMembership “”$userA””

    echo “All Done, “$userA” was created!”
    sleep 2
    exit
    else
    echo “Please Try Script Again!”
    exit 1
    fi

  25. Johny says:

    I followed this guide, and it all seemed to work. But when I restarted apache I got: “PHP Warning: PHP Startup: Unable to load dynamic library ‘/usr/lib/php/extensions/no-debug-non-zts-20060613/gd.so’ – (null) in Unknown on line 0″. I checked the folder /usr/lib/php/extensions/no-debug-non-zts-20060613/ and found a gd.so that was not empty. Any ideas?

  26. karlo says:

    Maybe check out also these snippets:

    Create & delete user accounts from the command line on Mac OS X

    http://codesnippets.joyent.com/posts/show/1374

    Creating & deleting system service agent accounts on Mac OS X

    http://codesnippets.joyent.com/posts/show/1405

  27. Cherooo says:

    Articles very interested, thank you very much

  28. Neil says:

    Rusty,

    When i run your script (above) on 10.5.6 i get the following after typing a username that i for sure know doesn’t exist on my system:

    “The username “?? already exists”

    Any ideas?

    -N

  29. [...] the new commands use dscl (directory services client) for managing users and groups. its still a bit confusing and less straight forward than the normal unix commands , usermod, groupadd, etc.  [...]

  30. Farialima says:

    The script above works well (once you replace the non-ascii characters by ascii characters in it) but (sorry…) I’ve found script that does more things, such as creating automatically a new UniqueID, creating a default group for the user, etc…: http://codesnippets.joyent.com/tag/dscl#post1374

  31. iruamjs says:

    Well, here’s my problem….

    I have a macbook running OSX 10.5.5 that didn’t want to load in to osx…

    First of all, when i turned on my macbook, it would just show the gray screen with either a “Prohibition Sign” or a flashing folder with a “?” on it.

    I entered the Mac OSX installer from a Boot Disc, and i realized that my home folder is renamed to “root”, which I suppose is the problem (original name was MacMau).

    I did all the steps recommended by Ivan (thx btw =]) and I think it loads osx, but still, all I get is a blue screen with the mouse pointer on it, which i can move. But still, it doesnt load any users, or a Login window.

    I’m sort of a newbie at all this, so I would appreciate if any help would be given as if it were for a 10 yr old…

    thanks for taking the time to read my problem, and thx in advance for any help that can be provided.

    I really miss my computer and the delightful voice of Vicky telling me the time every half an hour.. xP

  32. [...] users through bash from these two sites, Mac OS X: Creating a new user from the command-line and How to: Add a user from the OS X command line, works with Leopard! – OS X Daily. The important thing about the script is that it creates the user’s home directory on an external [...]

  33. bTi says:

    Thanks a million! I was able to use this in sigle user mode, but I had to replace the solitary “/” with just “.”

    hope this helps…

  34. [...] in what command sequence you used to make the user account. this is what i was working from: How to: Add a user from the OS X command line, works with Leopard! – OS X Daily Following that I ran into problems with creating the home directory and upon reboot into the gui it [...]

  35. slylabs13 says:

    I’d like to remove a user from the Admin group. I ssh’d in as root and tried:

    dscl . -delete /Groups/admin GroupMembership testadmn

    The command completed without error but the user account still shows up as an administrator.

  36. chitra says:

    when I try to go launch dscl

    I got error message

    launch_msg() : Socket is not connected.

    How can I go further ?

  37. [...] dscl / -create /Users/yourname dscl / -create /Users/yourname UserShell /bin/bash dscl / -create /Users/yourname RealName "yourfullname" dscl / -create /Users/yourname UniqueID 503 dscl / -create /Users/yourname PrimaryGroupID 1000 dscl / -create /Users/yourname NFSHomeDirectory /Local/Users/yourname source here: How to: Add a user from the OS X command line, works with Leopard! – OS X Daily [...]

  38. Thia says:

    Can someone help me I’m running mac os x 10 5 8
    I need instructions on how to set up a root user account I guess. Filevault has locked me out. I have no idea what’s going on or what I’m doing.

  39. whatforks says:

    if you do not know a filevault password you can not recover the files protected by it as far as i know

    you can add a root user by using the command above or just by going to the user accounts pref pane and adding a new admin user which is a lot easier. i think the entire point of the tip above is for advanced unix geeks who want to roll their 12 sided dice instead of clicking icons.

  40. J. Isserlis says:

    Just read this lot, rather late.
    Quick comments on shell script usage of grep etc. to test for existing user: no need for intermediate variable (by the way, avoid names like $test, too near to test(1) programme name): grep(1) returns 0 on match, 1 otherwise, so:

    DSCL=/usr/bin/dscl # avoid aliases, scripts, spoof.
    GREP=/usr/bin/grep

    function UserExists {
    $DSCL. -list /Users | $GREP$1 > /dev/null 2>&1
    # redirection removes stdout/stderr, XPG4 grep has “-q”
    return $?
    }

    USER=$1
    if UserExists $USER; then
    echo do whatever ….
    else
    echo $0: $USER not found >&2
    exit 1 #or try again or ….
    fi

    Also, when reading password, use stty -echo and stty echo
    e.g.
    echo -n Enter password
    stty -echo
    read P1
    stty echo

    Who knows who is looking over your shoulder.

  41. [...] osxdaily.com article September 17, 2010 10:06 am Tim Yates Thanks. The man pages tell you what commands you can use, but don’t give you any help on what fields to use and what to set them to. I was just going to copy the config from another account, but this gives a good example. September 17, 2010 11:12 am Gordon Davisson For a hidden system account, take a look at some existing system accounts for better examples. E.g. `dscl /Local/Default -read /Users/_sshd` (`dscl /Local/Default -ls /Users` will get you a list of local accounts). Note that you don’t have to set all attributes; GeneratedUID is generated randomly, and RecordType is automatic metadata. Also, most OS X system accounts have a primary account name that starts with underscore, and an alias without it for backward compatibility; I recommend using the underscore convention, but don’t bother with the plain alias unless you need to. September 18, 2010 1:45 am [...]

  42. [...] You’ll need a different dscl command for various user attributes. There is a guide for a standard-type user account here: http://osxdaily.com/2007/10/29/how-to-add-a-user-from-the-os-x-command-line-works-with-leopard/ [...]

  43. Drew says:

    It may be easier to install the free OSX server tools. Open up Workgroup Manager & select the local directory node, then you can import a text file of users laid out like so…

    Username:Password:Uid:Gid:Dist-Name:Homedir:Shell

    It is the standard record format so you could also do the import via the ‘dsimport’ command line tool, specifying ‘–template=StandardUser’ option.

  44. BAdger says:

    Thanks Rusty, but in single user mode how does one invoke the script, and where should it be stored for the ./makeuser.sh command to work? If I save the .sh file to the desktop and add the path to it (ie sudo ./Users/jay/Desktop/makeuser.sh) it fails to be run.

    THANKS

  45. Mik3Silv3r says:

    The scripts works?
    I have a PowerBook G4, but the user is a standar user…. and if i reboot with cmd+s in the command line: rm /var/db/.AppleSetupDone
    tell me that this file is read only mode….
    now.. in your scripts use the command “SUDO”, then if i am not an admin… how execute this script???
    i dont have the admin user and password, i dont have the CD, how create or change de admin pass?

  46. I needed to make one important modification: instead of

    dscl / -create …

    I needed

    dscl . -create …

    But that’s a minor detail. If this were on StackOverflow or apple.stackexchange.com, I would definitely upvote it.

  47. tanvir says:

    i have a postfix mail server on 9.8.0 Darwin Kernel Version 9.8.0, but i can’t create mail account/user

    pls help any one

  48. Erin says:

    Thanks for the info – - I have found some really good posts.

Leave a Reply

 

Shop for Apple & Mac Deals on Amazon.com

Subscribe to OSXDaily

Subscribe to RSS Subscribe to Twitter Feed Follow on Facebook Subscribe to eMail Updates