Skip to content

Instantly share code, notes, and snippets.

@adiroiban adiroiban/
Last active Dec 17, 2018

What would you like to do?
Script to add a service account on OSX.
# This is free and unencumbered software released into the public domain.
# Created by Nils Kollandsrud and modified by Adi Roiban.
# Script for creating a new service account on OSX.
# It will create a dedicated group and username for the service account.
# usage: sh username
# Check that we are superuser (i.e. $(id -u) is zero)
if (( $(id -u) )) ; then
echo "This script needs to run as root"
exit 1
UserNameNotUnused=$(dscacheutil -q user | grep 'name: '$NEWUSERNAME)
if [ "$UserNameNotUnused" != "" ]; then
echo "User $NEWUSERNAME already exists. Creation aborted!"
exit 1
# User does not exists, so we can go and create it.
NEXTUID=$(dscl . -list /Users UniqueID | awk 'BEGIN{i=0}{if($2>i)i=$2}END{print i+1}')
NEXTGID=$(dscl . -list /Groups PrimaryGroupID | awk 'BEGIN{i=0}{if($2>i)i=$2}END{print i+1}')
printf "Ready to create user/group $NEWUSERNAME with uid: $NEXTUID and gid: $NEXTGID\nEnter YES to continue\n"
if [ "$CONFIRMATION" != "YES" ] ; then
echo "Aborted as confirmation was not given!"
exit 1
dscl . create /Groups/$NEWUSERNAME
dscl . create /Groups/$NEWUSERNAME PrimaryGroupID $NEXTGID
dscl . create /Groups/$NEWUSERNAME Password '*'
dscl . create /Users/$NEWUSERNAME
dscl . create /Users/$NEWUSERNAME UniqueID $NEXTUID
dscl . create /Users/$NEWUSERNAME PrimaryGroupID $NEXTGID
dscl . create /Users/$NEWUSERNAME UserShell /usr/bin/false
dscl . create /Users/$NEWUSERNAME NFSHomeDirectory /var/empty
dscl . create /Users/$NEWUSERNAME Password '*'
dscl . delete /Users/$NEWUSERNAME PasswordPolicyOptions
dscl . delete /Users/$NEWUSERNAME AuthenticationAuthority
echo "$NEWUSERNAME service account has been created."
echo "User ID: $NEXTUID"
echo "Group ID: $NEXTGID"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.