Skip to content

Instantly share code, notes, and snippets.

@dfang
Forked from igorvoltaic/useradd.sh
Created June 13, 2023 03:37
Show Gist options
  • Save dfang/e012d4df8c33e06e38d469381b2872bf to your computer and use it in GitHub Desktop.
Save dfang/e012d4df8c33e06e38d469381b2872bf to your computer and use it in GitHub Desktop.
Create new user using command line in Mac OS X. Do not forget to set correct permissions for the file.
#!/bin/sh
if [[ `id -u` != 0 ]]; then
echo "Must be root to run script"
exit
fi
read -p "Enter user name and press [ENTER]: " UserName
if [[ $UserName == `dscl . -list /Users UniqueID | awk '{print $1}' | grep -w $UserName` ]]; then
echo "User already exists!"
exit 0
fi
read -p "Enter real name and press [ENTER]: " RealName
read -p "Enter PrimaryGroupID (80 - admin, 20 - user) and press [ENTER]: " PrimaryGroupID
LastID=`dscl . -list /Users UniqueID | awk '{print $2}' | sort -n | tail -1`
NextID=$((LastID + 1))
. /etc/rc.common
dscl . create /Users/$UserName
dscl . create /Users/$UserName RealName $RealName
read -p "Enter password hint and press [ENTER]: " PasswordHint
dscl . create /Users/$UserName hint $PasswordHint
PasswordHint=0
echo " "
read -s -p "Enter Account Password and press [ENTER]: " AccountPassword
echo " "
read -s -p "Enter Account Password again and press [ENTER]: " AccountPasswordRepeat
if [[ $AccountPassword == $AccountPasswordRepeat ]]; then
dscl . passwd /Users/$UserName $AccountPassword
AccountPassword=0
else
echo "Passwords do not match!"
exit 1
fi
echo " "
dscl . create /Users/$UserName UniqueID $NextID
dscl . create /Users/$UserName PrimaryGroupID $PrimaryGroupID
dscl . create /Users/$UserName UserShell /bin/bash
dscl . create /Users/$UserName NFSHomeDirectory /Users/$UserName
createhomedir -u $UserName -c
echo " "
echo "New user `dscl . -list /Users UniqueID | awk '{print $1}' | grep -w $UserName` has been created with unique ID `dscl . -list /Users UniqueID | grep -w $UserName | awk '{print $2}'`"
@dfang
Copy link
Author

dfang commented Jun 13, 2023

@dfang
Copy link
Author

dfang commented Jun 13, 2023

delete a user, list users, show user information
https://medium.com/macoclock/how-to-delete-a-user-account-on-macos-54623c84f336

sudo /usr/bin/dscl . -delete /Users/dylan

sudo dscl . list /Users | grep -v "^_"

sudo /usr/bin/dscl . -read /Users/dylan

@dfang
Copy link
Author

dfang commented Jun 13, 2023

logout user from terminal
https://apple.stackexchange.com/a/230972

sudo launchctl bootout gui/$(id -u <username>)
or
sudo launchctl bootout user/$(id -u <username>)

@dfang
Copy link
Author

dfang commented Jun 24, 2023

restart sshd on mac

sudo launchctl unload /System/Library/LaunchDaemons/ssh.plist
sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment