Skip to content
This repository has been archived by the owner on Mar 1, 2018. It is now read-only.

Commit

Permalink
Re-wrote preflight/postflight scripts in python, added some features,…
Browse files Browse the repository at this point in the history
… and updated Makefile task
  • Loading branch information
rickychilcott committed Oct 4, 2013
1 parent a0c7802 commit 3f950f8
Show file tree
Hide file tree
Showing 4 changed files with 164 additions and 92 deletions.
8 changes: 4 additions & 4 deletions script/munki_scripts/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ ID = com.github.jnraine.munkiserver.clientscripts
PKG_OUT = munkiscripts.pkg
DMG_OUT = munkiscripts.dmg
TITLE = "MunkiServer Client Scripts"
FILES = postflight.rb preflight.rb
FILES = postflight preflight
FILE_DST = postflight preflight

VERSION = $(shell date -j +"%Y%m%d")
Expand All @@ -19,15 +19,15 @@ ifeq ($(shell git rev-parse --git-dir >/dev/null 2>&1; echo $$?),0) # we are in
endif
DMG2_OUT = munkiscripts-$(VERSION).dmg

all: dmg
all: clean dmg
pkg: $(PKG_OUT)
dmg: $(DMG_OUT)

$(PKG_OUT): $(FILES)
mkdir -p $(TMPDIR)$(TARGETPATH)
$(foreach var,$(FILES), cp $(var) $(TMPDIR)$(TARGETPATH);)
mv $(TMPDIR)$(TARGETPATH)/postflight.rb $(TMPDIR)$(TARGETPATH)/postflight
mv $(TMPDIR)$(TARGETPATH)/preflight.rb $(TMPDIR)$(TARGETPATH)/preflight
mv $(TMPDIR)$(TARGETPATH)/postflight $(TMPDIR)$(TARGETPATH)/postflight
mv $(TMPDIR)$(TARGETPATH)/preflight $(TMPDIR)$(TARGETPATH)/preflight
sudo chown -R root:wheel $(TMPDIR)
sudo chmod 755 $(TMPDIR)
$(foreach var,$(FILE_DST), sudo chown root:wheel $(TMPDIR)$(TARGETPATH)/$(var);)
Expand Down
62 changes: 62 additions & 0 deletions script/munki_scripts/postflight
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#!/usr/bin/python
#encoding=utf-8

import os, random, re, sys
from munkilib import munkicommon

def munkiserver_url():
return munkicommon.pref("ManifestURL")

def cacert_file():
return munkicommon.pref("SoftwareRepoCACertificate")

def client_identifier():
ci = munkicommon.pref("ClientIdentifier")
if ci:
stripped_ci = re.search("(.*)(\.plist)", ci).group(1)
return stripped_ci
else:
exit(1)

def checkin_url():
return munkiserver_url() + "/checkin/" + client_identifier()

def managed_install_dir():
return munkicommon.pref("ManagedInstallDir")

def latest_managed_install_report_path():
return managed_install_dir() + "/ManagedInstallReport.plist"

def ssl_option():
if cacert_file():
return "--cacert \"{1}\"".format(cacert_file())
else:
return ""

def timeout_option():
if munkicommon.pref("PostflightTimeout"):
timeoutVal = munkicommon.pref("PostflightTimeout")
else:
timeoutVal = 90

return "--max-time {timeout}".format(timeout=timeoutVal)

def in_debug_or_test_mode():
if len(sys.argv) == 2 and (sys.argv[1] == "debug" or sys.argv[1] == "test"):
return True
else:
return False

def system_profiler_plist():
tmp_path = "/tmp/system_profiler_{random}.plist".format(random=random.randint(0,1000))
os.popen("/usr/sbin/system_profiler -xml SPHardwareDataType SPSoftwareDataType SPPrintersDataType > {path}".format(path=tmp_path))
return tmp_path

post_command = "/usr/bin/curl {timeout} {ssl} --form \"managed_install_report_plist=@{lmirp}\" --form \"system_profiler_plist=@{spp}\" {cu}".format(timeout=timeout_option(), ssl=ssl_option(), lmirp=latest_managed_install_report_path(), spp=system_profiler_plist(), cu=checkin_url())

if in_debug_or_test_mode():
print post_command
exit(0)
else:
os.popen(post_command)
exit(0)
88 changes: 0 additions & 88 deletions script/munki_scripts/postflight.rb

This file was deleted.

98 changes: 98 additions & 0 deletions script/munki_scripts/preflight
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
#!/usr/bin/python
#encoding=utf-8

#######################################################################################################
# This preflight script will do two things, 1) Set ClientIdentifer and 2) Block Updates, if applicable
#
# ClientIdenfier is set to mac_address_en0.plist, (eg. ab:ab:ab:ab:ab.plist)
#
# This preflight script will Block Updates during the specified time, as long it is in `auto` mode and
# the current time is int the appropriate range. Set the range, by setting the following keys in
# the /Library/Preferences/ManagedInstalls.plist file
#
# BlockUpdateStartTime - set to the start time in military, (e.g. "08:00")
#
# BlockUpdateEndTime - set to the end time in military, (e.g. "18:00")
#
# BlockUpdateDays - set to days the block should take effect, defaults to all days. You can NOT set
# the value or set it to "All". If you would only like a specific set of days, define#
# define the value in a string like "0, 3, 5" to only block on Mon, Wed, Fri.
# 0 is Monday, 7 is Sunday
#
#######################################################################################################

import os, sys, time, commands, datetime
from dateutil.parser import parse

from munkilib import munkicommon

def set_client_identifier(ci):
"""set ClientIdentifier based on MAC Address"""
munkicommon.set_pref("ClientIdentifier", ci)

def get_mac_address(iface):
"""docstring for get_mac_address"""
val = os.popen("ifconfig %s | awk '/ether/ {print $2}'" % iface).read().rstrip()
val += '.plist'
return val

def parseTimePref(pref):
prefValue = munkicommon.pref(pref)
if prefValue:
return parse(prefValue)
else:
return ''

def current_day():
"""Return the day of the week as an integer, where Monday is 0 and Sunday is 6."""
return datetime.datetime.localtime().weekday()

def current_time():
"""Return the current time in military format"""
return

def should_block_updates():
if (in_blocked_mode() and in_blocked_day() and in_blocked_time()):
return True
else:
return False

def in_blocked_mode():
runMode = sys.argv[1]
if (runMode == 'auto'):
return True
else:
return False

def in_blocked_time():
startTime = parseTimePref('BlockUpdateStartTime')
endTime = parseTimePref('BlockUpdateEndTime')
timeNow = parse(commands.getoutput("date"))
timeNow = timeNow.replace(tzinfo = None) # Strip the timezone info

if (startTime and endTime) and (startTime <= timeNow) and (timeNow <= endTime):
return True
else:
return False

def in_blocked_day():
blockedUpdateDays = munkicommon.pref('BlockUpdateDays')
todayNum = time.strftime('%w')

if (blockedUpdateDays == None) or (blockedUpdateDays == 'All') or (blockedUpdateDays == ''):
return True
else:
blockedDays = [day.strip() for day in blockedUpdateDays.split(',')]
return todayNum in blockedDays

# Set Client Identifier
mac_address = get_mac_address('en0')
set_client_identifier(mac_address)

# Should we block updates or continue on?
if should_block_updates():
print 'Updates have been blocked at this time.'
sys.exit(1)
else:
print 'Updates will continue at this time.'
sys.exit(0)

0 comments on commit 3f950f8

Please sign in to comment.