Cloning Macs via the Command Line

Recently, I’ve been doing a lot of cloning/imaging of machines. At a certain point, Carbon Copy Cloner and Disk Utility (or any GUI tool), doesn’t cut it. CCC of course started out as a wrapper for asr and there are guides for using asr for disk imaging online.

I’ve written a slick set of scripts that are streamlined for my purposes (automatically finding the mountpoints for sources and targets etc), but there’s probably some general stuff worth sharing…

Before cloning, I have a script that ‘preps’ the machine. This includes running periodic [daily|weekly|monthly] and clearing the caches:

sudo rm -rf /Library/Caches/*
sudo rm -rf /System/Library/Caches/*
sudo rm -rf /private/var/root/Library/Caches/*
sudo rm -rf ~/Library/Caches/*

Making the “master” image is pretty straightforward:

diskutil unmount "$volume"
time hdiutil create "$dmg" -format UDZO -nocrossdev -srcdevice "$device"
time asr imagescan --source "$dmg"

(I use a combination of time and overall timing recorders with date +%s epoch math to get proper performance numbers)

And cloning is even simpler:

time asr restore --source "$1" --target "$device" --erase --noprompt

Using --erase is essential to doing block-level writes and is a magnitude faster and more reliable.

Lastly, and what probably makes this writeup somewhat useful, I have some additional code that renames the hard drive and the machine name:

diskutil rename "$device" "$newname"
perl -p -i -e "s/$oldname/$newname/" "/Volumes/$newname/Library/Preferences/SystemConfiguration/preferences.plist"

The last step is preferable to using scutil because you can do it without rebooting, and it’ll already be renamed before there are any conflicts jumping on the network (which leads to the dreaded “(2)” problem).

With these scripts, I build a fully production ready clone in about 10 minutes flat.

Missing at this point:

  • Screensaver preferences don’t clone for some reason, I probably need to find a similar plist setting and rewrite that
  • I want a keyboard that just has a “T” key.
  • I probably should build a launchd script to run a “first bootup” script for anything else that needs to happen.