Add / Remove Users to Local Group via SSH

Here’s another script I just made, loosely based off my other SSH script that adds or removes users from a group on their machine. I use it in my enterprise to remotely give users temporary admin access to install approved software. Hope it’s of use to you…


# Get machine hostname
repeat
	set HostName to ""
	set Dialog_1 to display dialog "Enter Mac Hostname:" default answer ""
	set HostName to text returned of Dialog_1
	
	# Ping hostname to determine availability
	try
		set ping to (do shell script "ping -c 1 " & HostName)
		set Dialog_2 to display dialog "Machine is Available" buttons "Continue" default button "Continue"
	on error
		set Dialog_3 to display dialog "Machine is Unavailable" buttons {"Next.", "Cancel"} default button "Next."
	end try
	if the button returned of the result is "Continue" then
		exit repeat
	end if
end repeat

# Get username and group
set User to ""
set Dialog_4 to display dialog "Enter username:" default answer "" buttons "Next" default button "Next"
set User to text returned of Dialog_4

set Group to ""
set Dialog_5 to display dialog "Enter Group:" default answer "" buttons "Go" default button "Go"
set Group to text returned of Dialog_5

# Get SSH credentials
if the button returned of Dialog_5 is "Go" then
	set AdminName to ""
	set Dialog_6 to display dialog "Admin name:" default answer ""
	set AdminName to text returned of Dialog_6
	set PassKey to ""
	set Dialog_7 to display dialog "Admin Password:" default answer "" with hidden answer
	set PassKey to text returned of Dialog_7
end if

# Add or Remove User from Group
set Dialog_8 to display dialog "Add or Remove User from Group:" buttons {"Add", "Remove"}
if the button returned of Dialog_8 is "Add" then
	
	# Open SSH Session
	tell application "Terminal"
		activate
		set ssh to (do script "ssh " & AdminName & "@" & HostName)
		delay 3
		(do script "yes" in window 1)
		delay 3
		(do script PassKey in window 1)
		delay 3
		
		#Add user to group
		(do script "dseditgroup -o edit -u " & AdminName & " -p -a " & User & " -t user " & Group in window 1)
		delay 1
		(do script PassKey in window 1)
		
		#Check membership
		(do script "dsmemberutil checkmembership -U " & User & " -G " & Group in window 1)
		delay 1
		(do script "exit" in window 1)
	end tell
	
else if the button returned of Dialog_8 is "Remove" then
	
	# Open SSH Session
	tell application "Terminal"
		activate
		set ssh to (do script "ssh " & AdminName & "@" & HostName)
		delay 3
		(do script "yes" in window 1)
		delay 3
		(do script PassKey in window 1)
		delay 3
		
		#Remove user from group
		(do script "dseditgroup -o edit -u " & AdminName & " -p -d " & User & " -t user " & Group in window 1)
		delay 1
		(do script PassKey in window 1)
		
		#Check membership
		(do script "dsmemberutil checkmembership -U " & User & " -G " & Group in window 1)
		delay 1
		(do script "exit" in window 1)
	end tell
end if