Module: Jamf::Utility
Overview
A collection of useful utility methods. Mostly for converting values between formats, parsing data, and user interaction. This module should be extended into the Jamf Module so all methods become module methods
Constant Summary collapse
- OS_TEN_MAXS =
Hash of 'minor' => 'maint' The maximum maint release for macOS 10.minor.maint e.g the highest release of 10.6 was 10.6.8, the highest release of 10.15 was 10.15.7
12 is the default for the current OS and higher (and hoping apple doesn't release 10.16.13)
{ 2 => 8, 3 => 9, 4 => 11, 5 => 8, 6 => 8, 7 => 5, 8 => 5, 9 => 5, 10 => 5, 11 => 6, 12 => 6, 13 => 6, 14 => 6, 15 => 7 }
- MAC_OS_MAXS =
Hash of 'major' => 'minor' The maximum minor release for macOS major.minor e.g. the highest release of 11 is 11.12
12 is the default for the current OS and higher (and hoping apple doesn't release, e.g., 11.13)
{ 11 => 12, 12 => 12, 13 => 12, 14 => 12, 15 => 12, 16 => 12, 17 => 12, 18 => 12, 19 => 12, 20 => 12 }
Instance Method Summary collapse
-
#api_object_class(name) ⇒ Class
Given a name, singular or plural, of a Jamf::APIObject subclass as a String or Symbol (e.g. :computer/'computers'), return the class itself (e.g. Jamf::Computer) The available names are the RSRC_LIST_KEY and RSRC_OBJECT_KEY values for each APIObject subclass.
-
#api_object_names ⇒ Hash
APIObject subclasses have singular names, and are, of course capitalized, e.g.
-
#array_to_rexml_array(element, list) ⇒ Array<REXML::Element>
Given an element name and an array of content, generate an Array of REXML::Element objects with that name, and matching content.
-
#devmode(setting) ⇒ Boolean
un/set devmode mode.
-
#devmode? ⇒ Boolean
is devmode currently on?.
-
#epoch_to_time(epoch) ⇒ Time?
Converts JSS epoch (unix epoch + milliseconds) to a Ruby Time object.
-
#escape_xml(string) ⇒ String
Given a string of xml element text, escape any characters that would make XML unhappy.
-
#expand_min_os(min_os) ⇒ Array
Converts an OS Version into an Array of equal or higher OS versions, up to some non-existant max, hopefully far in the future, currently 20.12.10.
-
#hash_to_rexml_array(hash) ⇒ Array<REXML::Element>
Given a simple Hash, convert it to an array of REXML Elements such that each key becomes an element, and its value becomes the text content of that element.
-
#humanize_secs(secs) ⇒ String
Very handy! lifted from stackoverflow.com/questions/4136248/how-to-generate-a-human-readable-time-range-using-ruby-on-rails.
-
#item_list_to_rexml_list(list_element, item_element, item_list, content = :name) ⇒ REXML::Element
Given an Array of Hashes with :id and/or :name keys, return a single REXML element with a sub-element for each item, each of which contains a :name or :id element.
-
#os_ok?(requirement, os_to_check = nil) ⇒ Boolean
Scripts and packages can have OS limitations.
-
#parse_jss_version(version) ⇒ Hash{Symbol => String, Gem::Version}
Parse a JSS Version number into something comparable.
-
#parse_plist(plist, symbol_keys: false) ⇒ Object
Parse a plist into a Ruby data structure.
-
#parse_time(a_datetime) ⇒ Object
a wrapper around Time.parse that returns nil for nil, zero, and empty values.
-
#processor_ok?(requirement, processor = nil) ⇒ Boolean
Scripts and packages can have processor limitations.
-
#prompt_for_password(message) ⇒ String
Prompt for a password in a terminal.
-
#stdin(line = 0) ⇒ String?
Retrive one or all lines from whatever was piped to standard input.
-
#superuser? ⇒ Boolean
Is this code running as root?.
-
#to_s_and_a(somedata) ⇒ Hash{:stringform => String, :arrayform => Array}
Given a list of data as a comma-separated string, or an Array of strings, return a Hash with both versions.
-
#xml_plist_from(data) ⇒ String
Convert any ruby data to an XML plist.
Instance Method Details
#api_object_class(name) ⇒ Class
Given a name, singular or plural, of a Jamf::APIObject subclass as a String or Symbol (e.g. :computer/'computers'), return the class itself (e.g. Jamf::Computer) The available names are the RSRC_LIST_KEY and RSRC_OBJECT_KEY values for each APIObject subclass.
402 403 404 405 406 407 |
# File 'lib/jamf/utility.rb', line 402 def api_object_class(name) klass = api_object_names[name.downcase.to_sym] raise Jamf::InvalidDataError, "Unknown API Object Class: #{name}" unless klass klass end |
#api_object_names ⇒ Hash
APIObject subclasses have singular names, and are, of course capitalized, e.g. 'Computer' But we often want to refer to them in the plural, or lowercase, e.g. 'computers' This method returns a Hash of the RSRC_LIST_KEY (a plural symbol) and the RSRC_OBJECT_KEY (a singular symbol) of each APIObject subclass, keyed to the class itself, such that both :computer and :computers are keys for Jamf::Computer and both :policy and :policies are keys for Jamf::Policy, and so on.
421 422 423 424 425 426 427 428 429 430 431 432 433 434 |
# File 'lib/jamf/utility.rb', line 421 def api_object_names return @api_object_names if @api_object_names @api_object_names ||= {} JSS.constants.each do |const| klass = JSS.const_get const next unless klass.is_a? Class next unless klass.ancestors.include? Jamf::APIObject @api_object_names[klass.const_get(:RSRC_LIST_KEY).to_sym] = klass if klass.constants.include? :RSRC_LIST_KEY @api_object_names[klass.const_get(:RSRC_OBJECT_KEY).to_sym] = klass if klass.constants.include? :RSRC_OBJECT_KEY end @api_object_names end |
#array_to_rexml_array(element, list) ⇒ Array<REXML::Element>
Given an element name and an array of content, generate an Array of REXML::Element objects with that name, and matching content. Given element name 'foo' and the array ['bar','morefoo'] The array of REXML elements would render thus:
<foo>bar</foo>
<foo>morefoo</foo>
464 465 466 467 468 469 470 471 472 473 |
# File 'lib/jamf/utility.rb', line 464 def array_to_rexml_array(element, list) raise Jamf::InvalidDataError, 'Arg. must be an Array.' unless list.is_a? Array element = element.to_s list.map do |v| e = REXML::Element.new(element) e.text = v e end end |
#devmode(setting) ⇒ Boolean
un/set devmode mode. Useful when coding - methods can call JSS.devmode? and then e.g. spit out something instead of performing some action.
633 634 635 |
# File 'lib/jamf/utility.rb', line 633 def devmode(setting) @devmode = setting == :on end |
#devmode? ⇒ Boolean
is devmode currently on?
641 642 643 |
# File 'lib/jamf/utility.rb', line 641 def devmode? @devmode end |
#epoch_to_time(epoch) ⇒ Time?
Converts JSS epoch (unix epoch + milliseconds) to a Ruby Time object
383 384 385 386 387 |
# File 'lib/jamf/utility.rb', line 383 def epoch_to_time(epoch) return nil if NIL_DATES.include? epoch Time.at(epoch.to_i / 1000.0) end |
#escape_xml(string) ⇒ String
Given a string of xml element text, escape any characters that would make XML unhappy.
* & => &
* " => "
* < => <
* > => >
* ' => '
447 448 449 |
# File 'lib/jamf/utility.rb', line 447 def escape_xml(string) string.gsub(/&/, '&').gsub(/"/, '"').gsub(/>/, '>').gsub(/</, '<').gsub(/'/, ''') end |
#expand_min_os(min_os) ⇒ Array
Converts an OS Version into an Array of equal or higher OS versions, up to some non-existant max, hopefully far in the future, currently 20.12.10
This array can then be joined with commas and used as the value of the os_requirements for Packages and Scripts.
It's unlikely that this method, as written, will still be in use by the release of macOS 20.12.10, but currently thats the upper limit.
Hopefully well before then JAMF will implement a “minimum OS” in Jamf Pro itself, then we could avoid the inherant limitations in using a method like this.
When the highest maint. release of an OS version is not known, because its the currently released OS version or higher, then this method assumes '12' e.g. '10.16.12', '11.12', '12.12', etc.
Apple has never released more than 11 updates to a version of macOS (that being 10.4), so hopefully 12 is enough
Since Big Sur might report itself as either '10.16' or '11.x.x', this method will allow for both possibilities, and the array will contain whatever iterations needed for both version numbers
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 |
# File 'lib/jamf/utility.rb', line 122 def (min_os) min_os = min_os.delete '>=' # split the version into major, minor and maintenance release numbers major, minor, maint = min_os.split('.') minor = 'x' if minor.nil? || minor == '0' maint = 'x' if maint.nil? || maint == '0' ok_oses = [] # Deal with 10.x.x up to 10.16 if major == '10' # In big sur with SYSTEM_VERSION_COMPAT # set, it will only ever report as `10.16` # So if major is 10 and minor is 16, ignore maint # and start explicitly at '10.16' if minor == '16' ok_oses << '10.16' # But for Catalina and below, we need to # expand things out else # e.g. 10.14.x # doesn't expand to anything if maint == 'x' ok_oses << "10.#{minor}.x" # e.g. 10.15.5 # expand to 10.15.5, 10.15.6, 10.15.7 else max_maint_for_minor = OS_TEN_MAXS[minor.to_i] (maint.to_i..max_maint_for_minor).each do |m| ok_oses << "#{major}.#{minor}.#{m}" end # each m end # if maint == x # now if we started below catalina, account for everything # up to 10.15.x ((minor.to_i + 1)..15).each { |v| ok_oses << "10.#{v}.x" } if minor.to_i < 15 # and add big sur with SYSTEM_VERSION_COMPAT ok_oses << '10.16' end # if minor == 16 # now reset these so we can go higher major = '11' minor = 'x' maint = 'x' end # if major == 10 # if the min os is 11.0.0 or equiv, and we aven't added 10.16 # for SYSTEM_VERSION_COMPAT, add it now ok_oses << '10.16' if ['11', '11.x', '11.x.x', '11.0', '11.0.0'].include?(min_os) && !ok_oses.include?('10.16') # e.g. 11.x, or 11.x.x # expand to 11.x, 12.x, 13.x, ... 20.x if minor == 'x' ((major.to_i)..20).each { |v| ok_oses << "#{v}.x" } # e.g. 11.2.x # expand to 11.2.x, 11.3.x, ... 11.12.x, # 12.x, 13.x, ... 20.x elsif maint == 'x' # first expand the minors out to their max # e.g. 11.2.x, 11.3.x, ... 11.12.x max_minor_for_major = MAC_OS_MAXS[major.to_i] ((minor.to_i)..max_minor_for_major).each do |m| ok_oses << "#{major}.#{m}.x" end # each m # then add the majors out to 20 ((major.to_i + 1)..20).each { |v| ok_oses << "#{v}.x" } # e.g. 11.2.3 # expand to 11.2.3, 11.2.4, ... 11.2.10, # 11.3.x, 11.4.x, ... 11.12.x, # 12.x, 13.x, ... 20.x else # first expand the maints out to 10 # e.g. 11.2.3, 11.2.4, ... 11.2.10 ((maint.to_i)..10).each { |mnt| ok_oses << "#{major}.#{minor}.#{mnt}" } # then expand the minors out to their max # e.g. 11.3.x, ... 11.12.x max_minor_for_major = MAC_OS_MAXS[major.to_i] ((minor.to_i + 1)..max_minor_for_major).each { |min| ok_oses << "#{major}.#{min}.x" } # then add the majors out to 20 ((major.to_i + 1)..20).each { |v| ok_oses << "#{v}.x" } end ok_oses end |
#hash_to_rexml_array(hash) ⇒ Array<REXML::Element>
Given a simple Hash, convert it to an array of REXML Elements such that each key becomes an element, and its value becomes the text content of that element
491 492 493 494 495 496 497 498 499 500 501 |
# File 'lib/jamf/utility.rb', line 491 def hash_to_rexml_array(hash) raise InvalidDataError, 'Arg. must be a Hash.' unless hash.is_a? Hash ary = [] hash.each_pair do |k, v| el = REXML::Element.new k.to_s el.text = v ary << el end ary end |
#humanize_secs(secs) ⇒ String
Very handy! lifted from stackoverflow.com/questions/4136248/how-to-generate-a-human-readable-time-range-using-ruby-on-rails
Turns the integer 834756398 into the string “26 years 23 weeks 1 day 12 hours 46 minutes 38 seconds”
655 656 657 658 659 660 661 662 663 |
# File 'lib/jamf/utility.rb', line 655 def humanize_secs(secs) [[60, :second], [60, :minute], [24, :hour], [7, :day], [52.179, :week], [1_000_000_000, :year]].map do |count, name| next unless secs > 0 secs, n = secs.divmod(count) n = n.to_i "#{n} #{n == 1 ? name : (name.to_s + 's')}" end.compact.reverse.join(' ') end |
#item_list_to_rexml_list(list_element, item_element, item_list, content = :name) ⇒ REXML::Element
Given an Array of Hashes with :id and/or :name keys, return a single REXML element with a sub-element for each item, each of which contains a :name or :id element.
e.g. :computers
e.g. :computer
535 536 537 538 539 540 541 |
# File 'lib/jamf/utility.rb', line 535 def item_list_to_rexml_list(list_element, item_element, item_list, content = :name) xml_list = REXML::Element.new list_element.to_s item_list.each do |i| xml_list.add_element(item_element.to_s).add_element(content.to_s).text = i[content] end xml_list end |
#os_ok?(requirement, os_to_check = nil) ⇒ Boolean
Scripts and packages can have OS limitations. This method tests a given OS, against a requirement list to see if the requirement is met.
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 |
# File 'lib/jamf/utility.rb', line 252 def os_ok?(requirement, os_to_check = nil) return true if requirement.to_s =~ /none/i return true if requirement.to_s == 'n' requirement = JSS.to_s_and_a(requirement)[:arrayform] return true if requirement.empty? os_to_check ||= `/usr/bin/sw_vers -productVersion`.chomp # convert the requirement array into an array of regexps. # examples: # "10.8.5" becomes /^10\.8\.5$/ # "10.8" becomes /^10.8(.0)?$/ # "10.8.x" /^10\.8\.?\d*$/ req_regexps = requirement.map do |r| if r.end_with?('.x') /^#{r.chomp('.x').gsub('.', '\.')}(\.?\d*)*$/ elsif r =~ /^\d+\.\d+$/ /^#{r.gsub('.', '\.')}(.0)?$/ else /^#{r.gsub('.', '\.')}$/ end end req_regexps.each { |re| return true if os_to_check =~ re } false end |
#parse_jss_version(version) ⇒ Hash{Symbol => String, Gem::Version}
Parse a JSS Version number into something comparable.
This method returns a Hash with these keys:
-
:major => the major version, Integer
-
:minor => the minor version, Integor
-
:maint => the revision, Integer (also available as :patch and :revision)
-
:build => the revision, String
-
:version => a Gem::Version object built from :major, :minor, :revision which can be easily compared with other Gem::Version objects.
NOTE: the :version value ignores build numbers, so comparisons only compare major.minor.maint
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 |
# File 'lib/jamf/utility.rb', line 560 def parse_jss_version(version) major, second_part, *_rest = version.split('.') raise Jamf::InvalidDataError, 'JSS Versions must start with "x.x" where x is one or more digits' unless major =~ /\d$/ && second_part =~ /^\d/ release, build = version.split(/-/) major, minor, revision = release.split '.' minor ||= 0 revision ||= 0 { major: major.to_i, minor: minor.to_i, revision: revision.to_i, maint: revision.to_i, patch: revision.to_i, build: build, version: Gem::Version.new("#{major}.#{minor}.#{revision}") } end |
#parse_plist(plist, symbol_keys: false) ⇒ Object
Parse a plist into a Ruby data structure. The plist parameter may be a String containing an XML plist, or a path to a plist file, or it may be a Pathname object pointing to a plist file. The plist files may be XML or binary.
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 |
# File 'lib/jamf/utility.rb', line 335 def parse_plist(plist, symbol_keys: false) require 'cfpropertylist' # did we get a string of xml, or a string pathname? case plist when String return CFPropertyList.native_types(CFPropertyList::List.new(data: plist).value, symbol_keys) if plist.include? '</plist>' plist = Pathname.new plist when Pathname true else raise ArgumentError, 'Argument must be a path (as a Pathname or String) or a String of XML' end # case plist # if we're here, its a Pathname raise Jamf::MissingDataError, "No such file: #{plist}" unless plist.file? CFPropertyList.native_types(CFPropertyList::List.new(file: plist).value, symbol_keys) end |
#parse_time(a_datetime) ⇒ Object
a wrapper around Time.parse that returns nil for nil, zero, and empty values.
317 318 319 320 321 |
# File 'lib/jamf/utility.rb', line 317 def parse_time(a_datetime) return nil if NIL_DATES.include? a_datetime Time.parse a_datetime.to_s end |
#processor_ok?(requirement, processor = nil) ⇒ Boolean
Scripts and packages can have processor limitations. This method tests a given processor, against a requirement to see if the requirement is met.
232 233 234 235 236 237 |
# File 'lib/jamf/utility.rb', line 232 def processor_ok?(requirement, processor = nil) return true if requirement.to_s.empty? || requirement =~ /none/i processor ||= `/usr/bin/uname -p` requirement == (processor.to_s.include?('86') ? 'x86' : 'ppc') end |
#prompt_for_password(message) ⇒ String
Prompt for a password in a terminal.
612 613 614 615 616 617 618 619 620 621 622 623 |
# File 'lib/jamf/utility.rb', line 612 def prompt_for_password() begin $stdin.reopen '/dev/tty' unless $stdin.tty? $stderr.print "#{} " system '/bin/stty -echo' pw = $stdin.gets.chomp("\n") puts ensure system '/bin/stty echo' end # begin pw end |
#stdin(line = 0) ⇒ String?
Retrive one or all lines from whatever was piped to standard input.
Standard input is read completely the first time this method is called and the lines are stored as an Array in the module var @stdin_lines
597 598 599 600 601 602 603 604 |
# File 'lib/jamf/utility.rb', line 597 def stdin(line = 0) @stdin_lines ||= ($stdin.tty? ? [] : $stdin.read.lines.map { |l| l.chomp("\n") }) return @stdin_lines.join("\n") if line <= 0 idx = line - 1 @stdin_lines[idx] end |
#superuser? ⇒ Boolean
Returns is this code running as root?.
583 584 585 |
# File 'lib/jamf/utility.rb', line 583 def superuser? Process.euid.zero? end |
#to_s_and_a(somedata) ⇒ Hash{:stringform => String, :arrayform => Array}
Given a list of data as a comma-separated string, or an Array of strings, return a Hash with both versions.
Some parts of the JSS require lists as comma-separated strings, while often those data are easier work with as arrays. This method is a handy way to get either form when given either form.
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 |
# File 'lib/jamf/utility.rb', line 298 def to_s_and_a(somedata) case somedata when nil valstr = '' valarr = [] when String valstr = somedata valarr = somedata.split(/,\s*/) when Array valstr = somedata.join ', ' valarr = somedata else raise Jamf::InvalidDataError, 'Input must be a comma-separated String or an Array of Strings' end # case { stringform: valstr, arrayform: valarr } end |
#xml_plist_from(data) ⇒ String
Convert any ruby data to an XML plist.
NOTE: Binary data is tricky. Easiest way is to pass in a Pathname or IO object (anything that responds to `read` and returns a bytestring) and then the CFPropertyList.guess method will read it and convert it to a Plist <data> element with base64 encoded data. For more info, see CFPropertyList.guess
370 371 372 373 374 375 |
# File 'lib/jamf/utility.rb', line 370 def xml_plist_from(data) require 'cfpropertylist' plist = CFPropertyList::List.new plist.value = CFPropertyList.guess(data, convert_unknown_to_string: true) plist.to_str(CFPropertyList::List::FORMAT_XML) end |