Bash hell - Making OS X users admin

Status
Not open for further replies.

algebraist

Ars Scholae Palatinae
1,370
So i've been tasked at work to write a script that reads a txt file from a server share and makes the specified users local admin on our OS X boxes.

The file itself consists of a string of entries such as this:-

Code:
**computer name*:ADD:Administrator:domain\username
**computer name*:ADD:Administrator:domain\username,domain\username2

Code:
#!/bin/bash

# Set up needed variables here

macname=$( scutil --get ComputerName )
adminfile="/var/tmp/localadmins.txt"
OIFS=$IFS
IFS=$'\n'

# Mount fileshare where local admin file is kept.

mkdir /Volumes/SYSVOL
mount -o nobrowse -r -t smbfs //**domain controller**/SYSVOL /Volumes/SYSVOL

# Copy localadmin file to temp folder

cp /Volumes/SYSVOL/**path to file**/localadmins.txt /var/tmp/localadmins.txt

# Unmount and clean up fileshare.

diskutil umount force /Volumes/SYSVOL

# Read admin rights file line by line and process.

cat $adminfile | while read line
do

# Grab the name of the computer from the current line of the file

   compname=$( echo "${line}" | cut -d : -f 1 )

# Find out how many users are listed by counting the commas
   
   usercount=$( echo $((`echo ${line} | sed 's/[^,]//g' | wc -m`-1)) )

# Does the current computer name match the one in the file?
   
   if [ $macname = $compname ];
   then

# Loop to check name(s) are present on the mac and process them into the admin group.   

      for (( loop=0; loop<=usercount; loop++ ))
      do

	 field=$(($loop + 1))
         username=$( echo "${line}" | cut -d : -f 4 | cut -d "," -f ${field} | cut -c10- )
         
# Does specified user exist on the system in /Users? Loop round and if so place in admin group.
      
         for Account in `ls /Users`
         do

            if [[ $Account == $username ]];
            then
               dscl . -merge /Groups/admin GroupMembership "$username"
            fi
         done
      done
   fi
done

# Clean up and finish

IFS=$OIFS
rm /var/tmp/localadmins.txt
exit 0

The problem is that it doesn't work! Oh the loops all work and it does make sure things are present but ... the damn dscl command (and the dseditgroup -o edit -a $username -t user admin one before it) fail to work. dscl doesn't return any messages. The dseditgroup command returns a "record not found" message.

The really nasty part is that either command run on it's own actually works. The users in question are AD network users.
 

Stanley Turnteen

Ars Scholae Palatinae
856
Are you sure you've eliminated the domain\ prefix from each username? I assume that's what cut -c10- is intended to do, but without knowing your domain its possible you have an off-by-one error in there.

Also, if the file gets created on a Windows system, it's likely that it has CRLF line endings. You are splitting on \n, so the last username in the line is actually domain\username{CR}. OS X doesn't include the dos2unix/unix2dos utilities; you can get them from Homebrew/MacPorts or just nuke the stray CRs with sed or tr.
 

algebraist

Ars Scholae Palatinae
1,370
Good points, but yes I have checked extensively and it does "appear" to work. One odd thing while I was testing the script: the \ in the domain\username is being stripped out in the while read line. It doesn't seem to make any difference however.

I had echo $variable all over the script so as far as I can tell, it's all being processed correctly. I could still be wrong on this however.

I'm not the greatest with sed if i'm honest. (pretty appalling actually). How should I do that?
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
There are lots of problems with this script:
  • Don't use a hardcoded temporary file name. Use mktemp to create a filename, and use the 'trap' command to ensure it is deleted after the script exits:
    Code:
    TEMP=`mktemp`
    trap "rm -f \"$TEMP\"" EXIT
    Though I wouldn't do that at all and simply read the file off the file share.
  • Setting IFS and OFS isn't necessary in this script. The read builtin always assigns the remainder of the line to the last variable.
  • The '-r' argument to read will cause backslashes to lose their meaning as an escape character.
  • There's no need to count the number of users per line and use a counting for loop. Simply use the tr(1) command to convert the commas to newline, and use another standard read loop. This won't work if the usernames have commas in them (I sure hope not!).
  • Never use backticks / $() on something that might result in unbounded output (ls /Users). I think that OS X has a better way to check for membership, but I don't know what it is personally.
 

algebraist

Ars Scholae Palatinae
1,370
I'll try and address your points in order LordHunter317

1) Hardcoded path may not be best practice but is acceptable in this case, mainly because OS X clears out /var/tmp on startup anyway.

2) I have to copy off the file from the fileshare as the Casper system we're using mounts network shares to run even the simplest of tasks. Occasionally you can get mount point conflicts where it tries to mount the same share twice and your policy fails.

3) I now set IFS as a precaution as there's been a few occasions on OS X where it didn't do that for me.

4) OS X does have a dsmembercache checkmembership command but it's output is not too friendly to parse. Lots of grepping and cutting required. This way neatly avoids all the hidden users that exist on the OS that do various tasks such as lpadmin and others.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
algebraist":7borrkz4 said:
1) Hardcoded path may not be best practice but is acceptable in this case, mainly because OS X clears out /var/tmp on startup anyway.
That's not the problem. the problem is the hardcoded name is a security risk: an attacker could cause you to write the file somewhere not under your control, or overwrite your file with one of their own choosing.

You must always use random temporary names, generated from mktemp, in shell scripts. Nothing else is secure nor can be made secure.

2) I have to copy off the file from the fileshare as the Casper system we're using mounts network shares to run even the simplest of tasks. Occasionally you can get mount point conflicts where it tries to mount the same share twice and your policy fails.
That race condition can always happen. Mount the share elsewhere then.

3) I now set IFS as a precaution as there's been a few occasions on OS X where it didn't do that for me.
IFS is always set by the shell unless you explicitly unset it (don't do that).
 

Stanley Turnteen

Ars Scholae Palatinae
856
LH317 makes good points; as a reformed OS X admin, let me make a couple more:

  • Always use dseditgroup, don't just poke shortnames into GroupMembership with dscl. dseditgroup puts user GUIDs into GroupMembers; opendirectoryd/DirectoryService prefers lookups by GUID, and it can save you from some sticky situations (such as if all your usernames change because you have to flip dsconfigad -namespace into forest mode).
  • I'm not sure why you care if the user has a home directory on the local system before you put them in the local admin group. What if they just haven't logged into that system yet, or it's been recently reimaged? If for some reason you do care, and you are using mobile (cached) accounts, checking dslocal will be much faster than looping over all the homedirs that might exist in /Users:

    Code:
    if dscl . -read "/Users/${username}" RecordName 2>/dev/null ; then
      # User account exists on system
    fi

    And if its necessary to check the existence of the homedir, look for the folder directly:

    Code:
    if [ -d "/Users/${username}" ]; then
      # Home folder exists
    fi
 
Status
Not open for further replies.