Useful scripts for macOS

Settings


Creating User Accounts

The following script walks through a simple process of creating user accounts.

#!/bin/bash

#Author  : Arun Patwardhan
#Date    : 28th July 2019
#Contact : arun@amaranthine.co.in
#Website : https://www.amaranthine.in
#Scope   : This script creates a user account on macOS.
#Arguments
     #argument 1 : user Name
     #argument 2 : password
     #argument 3 : Account Type
     #arguemnt 4 : Full Name
     #argument 5 : Primary Group ID

#NOTE       : This script must be run as sudo.
#DISCLAIMER : The author of this script provides it on an as is basis. The author is not repsonsible for any damages, loss of data or any other issue that may occur with
#             the use of this script. The user of this script must take due care to validate the script before use.
#WARNING    : Use caution while running scripts as root.

####################################################################################################
####################################################################################################
# VALUE FORMAT FOR THE ARGUMENTS
# USERNAME          : All lower case, one word.
# PASSWORD          : Should be a single word. 
# ACCOUNT TYPE      : One Word, "admin", "standard"
# REAL NAME         : Can be more than one word. If it is more than one word then it should be in quotes.
# PRIMARY GROUP ID  : Just a number. (80 -> admin, 20 -? user)
#
# SAMPLE USAGE
# sudo sh ./createUserAccount.sh  <USERNAME>  <PASSWORD>  <ACCOUNTTYPE>  <REALNAME>  <PRIMARYGROUPID>
# sudo sh ./createUserAccount.sh  ladmin  ladminpwd  admin  "Local Admin"  80
####################################################################################################
####################################################################################################

#Variables
USERNAME=""
PASSWORD=""
ACCOUNTTYPE=""
REALNAME=""
PRIMARYGROUPID=""

#1. Check to see if the script is being run as root
if [[ $EUID -ne 0 ]]; then
    echo "The script must be run as root."
    exit 1
fi

#2. Assign values to variables
USERNAME=$1
PASSWORD=$2
ACCOUNTTYPE=$3
REALNAME=$4
PRIMARYGROUPID=$5

#3. Check to see if all the arguments are passed
if [[ $USERNAME == "" || $PASSWORD == "" || $ACCOUNTTYPE == "" || $REALNAME == "" || $PRIMARYGROUPID == "" ]]; then
    echo "ERROR: Incorrect use of command. Please make sure all the arguments are passed in."
    echo "sudo sh ./createUserAccount.sh <USERNAME> <PASSWORD> <ACCOUNTTYPE> <REALNAME> <PRIMARYGROUPID>"
    echo "For Example"
    echo "sudo sh ./createUserAccount.sh ladmin ladminpwd admin ""Local Admin"" 80"
    exit 1
fi

echo $USERNAME $PASSWORD $ACCOUNTTYPE $REALNAME $PRIMARYGROUPID

. /etc/rc.common

#4. Create the user
#Before creating the user we need to make sure the user doesn't already exist.
if [[ $USERNAME == `dscl . -list /Users UniqueID | awk '{print $1}' | grep -w $USERNAME` ]]; then
    echo "The User already exists. Please use another username"
    exit 0
fi

dscl . create /Users/$USERNAME

#5. Set the shell
dscl . create /Users/$USERNAME UserShell /bin/bash

#6. Set the real name
dscl . create /Users/$USERNAME RealName "$REALNAME"

#7. Set the Unique ID
LASTUSEDID=`dscl . -list /Users UniqueID | awk '{print $2}' | sort -n | tail -1`
echo $LASTUSEDID
NEXTAVAILABLEID=$((LASTUSEDID + 1))

dscl . create /Users/$USERNAME UniqueID $NEXTAVAILABLEID

#8. Set the Primary Group
dscl . create /Users/$USERNAME PrimaryGroupID $PRIMARYGROUPID

#9. Set the password
dscl . passwd /Users/$USERNAME $PASSWORD

#10. Create the Home Directory
dscl . create /Users/$USERNAME NFSHomeDirectory /Users/$USERNAME
createhomedir -u $USERNAME -c

#11. Add to admin group if account type is admin
if [[ $ACCOUNTTYPE == "admin" ]];
then
    dscl . -append /Groups/admin GroupMembership $USERNAME
fi

NOTE: To run this script make sure it is in a folder that is accessible to all users on the system. You may run into permission issues if you try to run this script from inside a user’s home folder.

Script Link.


Configuring Network settings

#!/bin/bash

#Author  : Arun Patwardhan
#Date    : 13th January 2020
#Contact : arun@amaranthine.co.in
#Website : https://www.amaranthine.in
#Scope   : This script configures the network settings for macOS
#Arguments
     #argument 1 : Location
     #argument 2 : Interface Name
     #argument 3 : IP Address
     #arguemnt 4 : Subnet
     #argument 5 : Router
     #argument 6 : DNS
     #argument 7 : Search Domain

#NOTE       : This script must be run as sudo.
#DISCLAIMER : The author of this script provides it on an as is basis. The author is not repsonsible for any damages, loss of data or any other issue that may occur with
#             the use of this script. The user of this script must take due care to validate the script before use.
#WARNING    : Use caution while running scripts as root.

####################################################################################################
####################################################################################################
# VALUE FORMAT FOR THE ARGUMENTS
#
# LOCATION      : Single word as a string. 'Classroom'
# INTERFACENAME : Single word as a string. 'Classroom'
# INTERFACETYPE : This can be more than one word. If it is more than one word then place it in quotes.
#                 Run the command `networksetup -listallhardwareports` to get a list of available ports.
# IPADDRESS     : It should be in IP Address format. 192.168.1.29
# SUBNETADDRESS : It should be in Subnet Mask format. 255.255.255.0
# ROUTERADDRESS : It should be in IP Address format. 192.168.1.1
# DNS           : It should be in IP Address format. 192.168.1.1
# SEARCHDOMAIN  : Single word with no space. Typical the search domain of the company. amaranthine.in

# SAMPLE USAGE
# sudo sh ./configureNetwork.sh <LOCATION> <INTERFACE NAME> <INTERFACE TYPE> <IP ADDRESS> <SUBNET> <ROUTER ADDRESS> <DNS ADDRESS> <SEARCH DOMAIN>
# sudo sh ./configureNetwork.sh Classroom Classroom Wi-Fi 192.168.1.100 255.255.0.0 192.168.1.1 192.168.1.1 amaranthine.in
####################################################################################################
####################################################################################################

#Variables
LOCATION=""
INTERFACENAME=""
INTERFACETYPE=""
IPADDRESS=""
SUBNETADDRESS=""
ROUTERADDRESS=""
DNS=""
SEARCHDOMAIN=""

#1. Check to see if the script is being run as root
if [[ $EUID -ne 0 ]]; then
    echo "The script must be run as root."
    exit 1
fi

#2. Assign values to variables
LOCATION=$1
INTERFACENAME=$2
INTERFACETYPE=$3
IPADDRESS=$4
SUBNETADDRESS=$5
ROUTERADDRESS=$6
DNS=$7
SEARCHDOMAIN=$8

#echo $1 $2 $3 $4 $5 $6 $7 $8

echo $LOCATION $INTERFACENAME $INTERFACETYPE $IPADDRESS $SUBNETADDRESS $ROUTERADDRESS $DNS $SEARCHDOMAIN

#3. Check to see if all the arguments are passed
if [[ $LOCATION == "" || $INTERFACENAME == "" || $INTERFACETYPE == "" || $IPADDRESS == "" || $SUBNETADDRESS == "" || $ROUTERADDRESS == "" || $DNS == "" || $SEARCHDOMAIN == "" ]]; then
    echo "ERROR: Incorrect use of command. Please make sure all the arguments are passed in."
    echo "sudo sh ./configureNetwork.sh <LOCATION> <INTERFACE NAME> <INTERFACE TYPE> <IP ADDRESS> <SUBNET> <ROUTER ADDRESS> <DNS ADDRESS> <SEARCH DOMAIN>"
    echo "For Example"
    echo "sudo sh ./configureNetwork.sh Classroom Classroom Wi-Fi 192.168.1.100 255.255.0.0 192.168.1.1 192.168.1.1 amaranthine.in"
    echo "For a list of available ports:"
    networksetup -listallhardwareports
    exit 1
fi

#4. Create the location & switch settings to that location
networksetup -createlocation $LOCATION
networksetup -switchtolocation $LOCATION

#5. Create the network service interface for the given hardware port
networksetup -createnetworkservice $INTERFACENAME $INTERFACETYPE

#6. Set the network settings IP Address, Subnet, Router
networksetup -setmanual Classroom $IPADDRESS $SUBNETADDRESS $ROUTERADDRESS

#7. Set the DNS Server address for the network service
networksetup -setdnsservers $INTERFACENAME $DNS

#8. Set the search domain for the given interface
networksetup -setsearchdomains $INTERFACENAME $SEARCHDOMAIN

Script Link.


Set Energy Preferences

#!/bin/bash

#Author  : Arun Patwardhan
#Date    : 26th March 2020
#Contact : arun@amaranthine.co.in
#Website : https://www.amaranthine.in
#Scope   : This script configures the Disk images.
#Arguments

#NOTE       : This script must be run as sudo.
#DISCLAIMER : The author of this script provides it on an as is basis. The author is not repsonsible for any damages, loss of data or any other issue that may occur with
#             the use of this script. The user of this script must take due care to validate the script before use.
#WARNING    : Use caution while running scripts as root. THIS SCRIPT EXPECTS THE USER TO PROVIDE A USER ACCOUNT PASSWORD IN CLEAR TEXT. PLEASE USE CAUTION. IT WOULD BE RECOMMENDED TO MODIFY THIS SCRIPT IN A PRODUCTION ENVIRONMENT.

####################################################################################################
####################################################################################################
# SAMPLE USAGE
# sudo ./configureEnergyManagement.sh
####################################################################################################
####################################################################################################

#Variables
LOGFILE="/Users/Shared/configureEnergyManagement.log"
ENERGYMANAGEMENTREPORT="/Users/Shared/EnergyManagementReport.plist"
COMPREHENSIVEREPORT="/Users/Shared/ComprehensiveEnergyManagementReport.txt"

#1. Check to see if the script is being run as root
if [[ $EUID -ne 0 ]]; then
    echo "The script must be run as root."
    exit 1
fi

#2. Check to see if the log file exists
if [[ -f $LOGFILE ]]
then
    echo "$(date "+DATE: %Y-%m-%d%TIME: %H:%M:%S") File exists" >> $LOGFILE
else
    cd /Users/Shared/
    touch configureEnergyManagement.log
    echo "$(date "+DATE: %Y-%m-%d%TIME: %H:%M:%S") Created Folder" >> $LOGFILE
fi

#3. Schedule weekday shutdown
pmset repeat shutdown MTWRF 19:00:00
echo "$(date "+DATE: %Y-%m-%d%TIME: %H:%M:%S") Scheduling shutdown from Monday through Friday at 7:00 PM" >> $LOGFILE

#4. Enable power nap
pmset powernap 1
echo "$(date "+DATE: %Y-%m-%d%TIME: %H:%M:%S") Enabling powernap." >> $LOGFILE

#5. Generate report
defaults write $ENERGYMANAGEMENTREPORT PowerSource -dict-add Battery "$(pmset -g batt)"
defaults write $ENERGYMANAGEMENTREPORT PowerSource -dict-add Adapter "$(pmset -g adapter)"

defaults write $ENERGYMANAGEMENTREPORT SleepWake -dict-add Events "$(pmset -g sched)"
defaults write $ENERGYMANAGEMENTREPORT SleepWake -dict-add Count "$(pmset -g stats)"

defaults write $ENERGYMANAGEMENTREPORT Thermal -dict-add ThermalEvents "$(pmset -g therm)"

pmset -g everything >> $COMPREHENSIVEREPORT
echo "$(date "+DATE: %Y-%m-%d%TIME: %H:%M:%S") Generating energy report." >> $LOGFILE

Script Link.

Handy command to keep system awake. I use it when I am performing lengthy transfers of data to ensure that the system is awake.

#!/bin/bash

#Author  : Arun Patwardhan
#Date    : 26th March 2020
#Contact : arun@amaranthine.co.in
#Website : https://www.amaranthine.in
#Scope   : This script keeps the system awake.
#Arguments

#NOTE       : This script must be run as sudo.
#DISCLAIMER : The author of this script provides it on an as is basis. The author is not repsonsible for any damages, loss of data or any other issue that may occur with
#             the use of this script. The user of this script must take due care to validate the script before use.
#WARNING    : Use caution while running scripts as root. THIS SCRIPT EXPECTS THE USER TO PROVIDE A USER ACCOUNT PASSWORD IN CLEAR TEXT. PLEASE USE CAUTION. IT WOULD BE RECOMMENDED TO MODIFY THIS SCRIPT IN A PRODUCTION ENVIRONMENT.

####################################################################################################
####################################################################################################
# SAMPLE USAGE
# sudo ./keepAwake.sh
####################################################################################################
####################################################################################################

#Variables
LOGFILE="/Users/Shared/keepAwake.log"

#1. Check to see if the log file exists
if [[ -f $LOGFILE ]]
then
    echo "$(date "+DATE: %Y-%m-%d%TIME: %H:%M:%S") File exists" >> $LOGFILE
else
    cd /Users/Shared/
    touch keepAwake.log
    echo "$(date "+DATE: %Y-%m-%d%TIME: %H:%M:%S") Created Folder" >> $LOGFILE
fi

#2. Schedule weekday shutdown
caffeinate -dimsu

Script Link.


Miscellaneous Settings

#!/bin/bash

#Author  : Arun Patwardhan
#Date    : 26th March 2020
#Contact : arun@amaranthine.co.in
#Website : https://www.amaranthine.in
#Scope   : This script configures the different settings.
#Arguments

#NOTE       : This script must be run as sudo.
#DISCLAIMER : The author of this script provides it on an as is basis. The author is not repsonsible for any damages, loss of data or any other issue that may occur with
#             the use of this script. The user of this script must take due care to validate the script before use.
#WARNING    : Use caution while running scripts as root.

####################################################################################################
####################################################################################################
# SAMPLE USAGE
# ./configureSettings.sh
####################################################################################################
####################################################################################################

#Variables
LOGFILE="/Users/Shared/configureSettings.log"

#1. Check to see if the log file exists
if [[ -f $LOGFILE ]]
then
    echo "$(date "+DATE: %Y-%m-%d%TIME: %H:%M:%S") File exists" >> $LOGFILE
else
    cd /Users/Shared/
    touch collectSystemInformation.log
    echo "$(date "+DATE: %Y-%m-%d%TIME: %H:%M:%S") Created Folder" >> $LOGFILE
fi

#MARK: - Screen Capture
#2. Screen capture ----------
# Update the type of image produced when screen capture is taken
defaults write com.apple.screencapture type -string "jpg"
echo "$(date "+DATE: %Y-%m-%d%TIME: %H:%M:%S") Setting the screen capture image type to jpg." >> $LOGFILE

# Change the location where the screenshot is saved
defaults write com.apple.screencapture location /Users/Shared/
echo "$(date "+DATE: %Y-%m-%d%TIME: %H:%M:%S") Changing the location where screencaptures are saved to /Users/Shared/ Folder" >> $LOGFILE

# Take a screenshot
NAME=`date "+DATE:%Y-%m-%dTIME:%H:%M:%S"`
screencapture $NAME.pdf

#MARK: - Hide Files & Folders
#3. Show all the hidden items
defaults write com.apple.finder AppleShowAllFiles -bool true
# Relaunch finder for settings to take effect
killall Finder
echo "$(date "+DATE: %Y-%m-%d%TIME: %H:%M:%S") Setting the flag to show all hidden items to true." >> $LOGFILE

#4. Hide specific items
cd ~/Desktop/
touch demofile.txt
chflags hidden demofile.txt

#5. Unhide the previous item
chflags nohidden demofile.txt

#MARK: - Metadata & Spotlight
#6. View metadata for a file
cd ~/Desktop/
mdls demofile.txt >> /Users/Shared/demofileMetadata.txt

#7. Disable spotlight search for a volume
mdutil -d /Volumes/Info/

#8. Spotlight indexing status
mdutil -s /Volumes/Info/

#9. Search with spotlight
mdfind -onlyin ~/Desktop/ demo

#10. Viewing extended attributes
cd ~/Desktop/
xattr demofile.txt

Script Link.


2 thoughts on “Useful scripts for macOS

  1. Pingback: List of macOS Terminal commands | Arun Patwardhan's Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s