Module: JSS

Defined in:
lib/jss.rb,
lib/jss/client.rb,
lib/jss/server.rb,
lib/jss/utility.rb,
lib/jss/version.rb,
lib/jss/composer.rb,
lib/jss/validate.rb,
lib/jss/api_object.rb,
lib/jss/exceptions.rb,
lib/jss/configuration.rb,
lib/jss/db_connection.rb,
lib/jss/api_connection.rb,
lib/jss/api_object/mdm.rb,
lib/jss/xml_workaround.rb,
lib/jss/api_object/site.rb,
lib/jss/api_object/user.rb,
lib/jss/api_object/ebook.rb,
lib/jss/api_object/group.rb,
lib/jss/api_object/policy.rb,
lib/jss/api_object/script.rb,
lib/jss/api_object/account.rb,
lib/jss/api_object/ibeacon.rb,
lib/jss/api_object/package.rb,
lib/jss/api_object/printer.rb,
lib/jss/api_object/sitable.rb,
lib/jss/api_object/vppable.rb,
lib/jss/api_object/webhook.rb,
lib/jss/client/jamf_binary.rb,
lib/jss/client/jamf_helper.rb,
lib/jamf/client/jamf_binary.rb,
lib/jamf/client/jamf_helper.rb,
lib/jss/api_object/building.rb,
lib/jss/api_object/category.rb,
lib/jss/api_object/computer.rb,
lib/jss/api_object/scopable.rb,
lib/jss/api_object/creatable.rb,
lib/jss/api_object/dock_item.rb,
lib/jss/api_object/locatable.rb,
lib/jss/api_object/matchable.rb,
lib/jss/api_object/updatable.rb,
lib/jss/api_object/department.rb,
lib/jss/api_object/extendable.rb,
lib/jss/api_object/peripheral.rb,
lib/jss/api_object/uploadable.rb,
lib/jss/api_object/criteriable.rb,
lib/jss/api_object/ldap_server.rb,
lib/jss/api_object/patch_title.rb,
lib/jss/api_object/purchasable.rb,
lib/jss/api_object/vpp_account.rb,
lib/jss/api_object/patch_policy.rb,
lib/jss/api_object/patch_source.rb,
lib/jss/api_object/categorizable.rb,
lib/jss/api_object/mobile_device.rb,
lib/jss/api_object/self_servable.rb,
lib/jss/client/management_action.rb,
lib/jamf/client/management_action.rb,
lib/jss/api_object/netboot_server.rb,
lib/jss/api_object/scopable/scope.rb,
lib/jss/api_object/advanced_search.rb,
lib/jss/api_object/mac_application.rb,
lib/jss/api_object/network_segment.rb,
lib/jss/api_object/peripheral_type.rb,
lib/jss/api_object/group/user_group.rb,
lib/jss/api_object/directory_binding.rb,
lib/jss/api_object/removable_macaddr.rb,
lib/jss/api_object/distribution_point.rb,
lib/jss/api_object/management_history.rb,
lib/jss/api_object/self_servable/icon.rb,
lib/jss/api_object/computer_invitation.rb,
lib/jss/api_object/extension_attribute.rb,
lib/jss/api_object/patch_title/version.rb,
lib/jss/api_object/restricted_software.rb,
lib/jss/api_object/criteriable/criteria.rb,
lib/jss/api_object/group/computer_group.rb,
lib/jss/api_object/configuration_profile.rb,
lib/jss/api_object/criteriable/criterion.rb,
lib/jss/api_object/directory_binding_type.rb,
lib/jss/api_object/software_update_server.rb,
lib/jss/api_object/app_store_country_codes.rb,
lib/jss/api_object/management_history/ebook.rb,
lib/jss/api_object/group/mobile_device_group.rb,
lib/jss/api_object/mobile_device_application.rb,
lib/jss/api_object/management_history/hashlike.rb,
lib/jss/api_object/computer/application_installs.rb,
lib/jss/api_object/management_history/policy_log.rb,
lib/jss/api_object/disk_encryption_configurations.rb,
lib/jss/api_object/management_history/audit_event.rb,
lib/jss/api_object/management_history/mdm_command.rb,
lib/jss/api_object/directory_binding_type/admitmac.rb,
lib/jss/api_object/directory_binding_type/centrify.rb,
lib/jss/api_object/patch_source/patch_external_source.rb,
lib/jss/api_object/patch_source/patch_internal_source.rb,
lib/jss/api_object/advanced_search/advanced_user_search.rb,
lib/jss/api_object/management_history/casper_remote_log.rb,
lib/jss/api_object/management_history/mac_app_store_app.rb,
lib/jss/api_object/management_history/mobile_device_app.rb,
lib/jss/api_object/directory_binding_type/open_directory.rb,
lib/jss/api_object/management_history/casper_imaging_log.rb,
lib/jss/api_object/management_history/computer_usage_log.rb,
lib/jss/api_object/management_history/screen_sharing_log.rb,
lib/jss/api_object/directory_binding_type/active_directory.rb,
lib/jss/api_object/management_history/user_location_change.rb,
lib/jss/api_object/advanced_search/advanced_computer_search.rb,
lib/jss/api_object/extension_attribute/user_extension_attribute.rb,
lib/jss/api_object/advanced_search/advanced_mobile_device_search.rb,
lib/jss/api_object/configuration_profile/osx_configuration_profile.rb,
lib/jss/api_object/extension_attribute/computer_extension_attribute.rb,
lib/jss/api_object/directory_binding_type/powerbroker_identity_services.rb,
lib/jss/api_object/extension_attribute/mobile_device_extension_attribute.rb,
lib/jss/api_object/configuration_profile/mobile_device_configuration_profile.rb

Overview

Licensed under the Apache License, Version 2.0 (the “Apache License”)

with the following modification; you may not use this file except in
compliance with the Apache License and the following modification to it:
Section 6. Trademarks. is deleted and replaced with:

6. Trademarks. This License does not grant permission to use the trade
   names, trademarks, service marks, or product names of the Licensor
   and its affiliates, except as required to comply with Section 4(c) of
   the License and to reproduce the content of the NOTICE file.

You may obtain a copy of the Apache License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the Apache License with the above modification is
distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Apache License for the specific
language governing permissions and limitations under the Apache License.

Defined Under Namespace

Modules: Categorizable, Composer, Creatable, Criteriable, DirectoryBindingType, Extendable, FileUpload, Locatable, MDM, ManagementHistory, Matchable, Purchasable, Scopable, SelfServable, Sitable, Updatable, Uploadable, VPPable, Validate, XMLWorkaround Classes: APIConnection, APIObject, APIRequestError, Account, AdvancedComputerSearch, AdvancedMobileDeviceSearch, AdvancedSearch, AdvancedUserSearch, AlreadyExistsError, AmbiguousError, AuthenticationError, AuthorizationError, BadRequestError, Building, Category, Client, Computer, ComputerExtensionAttribute, ComputerGroup, ComputerInvitation, Configuration, ConfigurationProfile, ConflictError, DBConnection, Department, DirectoryBinding, DiskEncryptionConfiguration, DistributionPoint, DockItem, EBook, ExtensionAttribute, FileServiceError, Group, IBeacon, Icon, InvalidConnectionError, InvalidDataError, LDAPServer, MacApplication, MissingDataError, MobileDevice, MobileDeviceApplication, MobileDeviceConfigurationProfile, MobileDeviceExtensionAttribute, MobileDeviceGroup, NetBootServer, NetworkSegment, NoSuchItemError, OSXConfigurationProfile, Package, PatchExternalSource, PatchInternalSource, PatchPolicy, PatchSource, PatchTitle, Peripheral, PeripheralType, Policy, Preferences, Printer, RemovableMacAddress, RestrictedSoftware, Script, Server, Site, SoftwareUpdateServer, TimeoutError, UnmanagedError, UnsupportedError, User, UserExtensionAttribute, UserGroup, VPPAccount, WebHook

Constant Summary collapse

MINIMUM_RUBY_VERSION =

The minimum Ruby version that works with this gem

'2.0.0'.freeze
MINIMUM_SERVER_VERSION =

The minimum JSS version that works with this module, as returned by the API in the deprecated 'jssuser' resource

'10.4.0'.freeze
TIME_ZONE_OFFSET =

The current local UTC offset as a fraction of a day (Time.now.utc_offset is the offset in seconds, 60*60*24 is the seconds in a day)

Rational(Time.now.utc_offset, 60 * 60 * 24)
TRUE_FALSE =

These are handy for testing values without making new arrays, strings, etc every time.

[true, false].freeze
NIL_DATES =

When parsing a date/time data into a Time object, these will return nil

[0, nil, '', '0'].freeze
BLANK =

Empty strings are used in various places

''.freeze
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
}
VERSION =

The version of ruby-jss

'1.6.7'.freeze
CONFIG =

The single instance of Configuration

JSS::Configuration.instance
DB_CNX =

The single instance of the DBConnection

DBConnection.instance
API =

Save the default connection in the API constant, mostly for backward compatibility.

@api
APP_STORE_COUNTRY_CODES =

The official names and two-letter codes for countries known to the App Store. These were retrieved from the Jamf Pro API endpoint in August 2020. They should be updated regularly. To do so using the Jamf Module, just replace this Hash with the one you get from:

Jamf::AppStoreCountryCodes.codes_by_name
{
  'Afghanistan' => 'AF',
  'Aland Islands' => 'AX',
  'Albania' => 'AL',
  'Algeria' => 'DZ',
  'American Samoa' => 'AS',
  'Andorra' => 'AD',
  'Angola' => 'AO',
  'Anguilla' => 'AI',
  'Antarctica' => 'AQ',
  'Antigua and Barbuda' => 'AG',
  'Argentina' => 'AR',
  'Armenia' => 'AM',
  'Aruba' => 'AW',
  'Australia' => 'AU',
  'Austria' => 'AT',
  'Azerbaijan' => 'AZ',
  'Bahamas' => 'BS',
  'Bahrain' => 'BH',
  'Bangladesh' => 'BD',
  'Barbados' => 'BB',
  'Belarus' => 'BY',
  'Belgium' => 'BE',
  'Belize' => 'BZ',
  'Benin' => 'BJ',
  'Bermuda' => 'BM',
  'Bhutan' => 'BT',
  'Bolivia, Plurinational State of' => 'BO',
  'Bosnia and Herzegovina' => 'BA',
  'Botswana' => 'BW',
  'Bouvet Island' => 'BV',
  'Brazil' => 'BR',
  'British Indian Ocean Territory' => 'IO',
  'Brunei Darussalam' => 'BN',
  'Bulgaria' => 'BG',
  'Burkina Faso' => 'BF',
  'Burundi' => 'BI',
  'Cambodia' => 'KH',
  'Cameroon' => 'CM',
  'Canada' => 'CA',
  'Cape Verde' => 'CV',
  'Cayman Islands' => 'KY',
  'Central African Republic' => 'CF',
  'Chad' => 'TD',
  'Chile' => 'CL',
  'China' => 'CN',
  'Christmas Island' => 'CX',
  'Cocos (Keeling) Islands' => 'CC',
  'Colombia' => 'CO',
  'Comoros' => 'KM',
  'Congo' => 'CG',
  'Congo, the Democratic Republic of the' => 'CD',
  'Cook Islands' => 'CK',
  'Costa Rica' => 'CR',
  "Cote d'Ivoire" => 'CI',
  'Croatia' => 'HR',
  'Cuba' => 'CU',
  'Cyprus' => 'CY',
  'Czech Republic' => 'CZ',
  'Denmark' => 'DK',
  'Djibouti' => 'DJ',
  'Dominica' => 'DM',
  'Dominican Republic' => 'DO',
  'Ecuador' => 'EC',
  'Egypt' => 'EG',
  'El Salvador' => 'SV',
  'Equatorial Guinea' => 'GQ',
  'Eritrea' => 'ER',
  'Estonia' => 'EE',
  'Ethiopia' => 'ET',
  'Falkland Islands (Malvinas)' => 'FK',
  'Faroe Islands' => 'FO',
  'Fiji' => 'FJ',
  'Finland' => 'FI',
  'France' => 'FR',
  'French Guiana' => 'GF',
  'French Polynesia' => 'PF',
  'French Southern Territories' => 'TF',
  'Gabon' => 'GA',
  'Gambia' => 'GM',
  'Georgia' => 'GE',
  'Germany' => 'DE',
  'Ghana' => 'GH',
  'Gibraltar' => 'GI',
  'Greece' => 'GR',
  'Greenland' => 'GL',
  'Grenada' => 'GD',
  'Guadeloupe' => 'GP',
  'Guam' => 'GU',
  'Guatemala' => 'GT',
  'Guernsey' => 'GG',
  'Guinea' => 'GN',
  'Guinea-Bissau' => 'GW',
  'Guyana' => 'GY',
  'Haiti' => 'HT',
  'Heard Island and McDonald Islands' => 'HM',
  'Holy See (Vatican City State)' => 'VA',
  'Honduras' => 'HN',
  'Hong Kong' => 'HK',
  'Hungary' => 'HU',
  'Iceland' => 'IS',
  'India' => 'IN',
  'Indonesia' => 'ID',
  'Iran, Islamic Republic of' => 'IR',
  'Iraq' => 'IQ',
  'Ireland' => 'IE',
  'Isle of Man' => 'IM',
  'Israel' => 'IL',
  'Italy' => 'IT',
  'Jamaica' => 'JM',
  'Japan' => 'JP',
  'Jersey' => 'JE',
  'Jordan' => 'JO',
  'Kazakhstan' => 'KZ',
  'Kenya' => 'KE',
  'Kiribati' => 'KI',
  "Korea, Democratic People's Republic of" => 'KP',
  'Korea, Republic of' => 'KR',
  'Kuwait' => 'KW',
  'Kyrgyzstan' => 'KG',
  "Lao People's Democratic Republic" => 'LA',
  'Latvia' => 'LV',
  'Lebanon' => 'LB',
  'Lesotho' => 'LS',
  'Liberia' => 'LR',
  'Libyan Arab Jamahiriya' => 'LY',
  'Liechtenstein' => 'LI',
  'Lithuania' => 'LT',
  'Luxembourg' => 'LU',
  'Macao' => 'MO',
  'Macedonia, the former Yugoslav Republic of' => 'MK',
  'Madagascar' => 'MG',
  'Malawi' => 'MW',
  'Malaysia' => 'MY',
  'Maldives' => 'MV',
  'Mali' => 'ML',
  'Malta' => 'MT',
  'Marshall Islands' => 'MH',
  'Martinique' => 'MQ',
  'Mauritania' => 'MR',
  'Mauritius' => 'MU',
  'Mayotte' => 'YT',
  'Mexico' => 'MX',
  'Micronesia, Federated States of' => 'FM',
  'Moldova, Republic of' => 'MD',
  'Monaco' => 'MC',
  'Mongolia' => 'MN',
  'Montenegro' => 'ME',
  'Montserrat' => 'MS',
  'Morocco' => 'MA',
  'Mozambique' => 'MZ',
  'Myanmar' => 'MM',
  'Namibia' => 'NA',
  'Nauru' => 'NR',
  'Nepal' => 'NP',
  'Netherlands' => 'NL',
  'Netherlands Antilles' => 'AN',
  'New Caledonia' => 'NC',
  'New Zealand' => 'NZ',
  'Nicaragua' => 'NI',
  'Niger' => 'NE',
  'Nigeria' => 'NG',
  'Niue' => 'NU',
  'Norfolk Island' => 'NF',
  'Northern Mariana Islands' => 'MP',
  'Norway' => 'NO',
  'Oman' => 'OM',
  'Pakistan' => 'PK',
  'Palau' => 'PW',
  'Palestinian Territory, Occupied' => 'PS',
  'Panama' => 'PA',
  'Papua New Guinea' => 'PG',
  'Paraguay' => 'PY',
  'Peru' => 'PE',
  'Philippines' => 'PH',
  'Pitcairn' => 'PN',
  'Poland' => 'PL',
  'Portugal' => 'PT',
  'Puerto Rico' => 'PR',
  'Qatar' => 'QA',
  'Reunion' => 'RE',
  'Romania' => 'RO',
  'Russian Federation' => 'RU',
  'Rwanda' => 'RW',
  'Saint Barthelemy' => 'BL',
  'Saint Helena, Ascension and Tristan da Cunha' => 'SH',
  'Saint Kitts and Nevis' => 'KN',
  'Saint Lucia' => 'LC',
  'Saint Martin (French part)' => 'MF',
  'Saint Pierre and Miquelon' => 'PM',
  'Saint Vincent and the Grenadines' => 'VC',
  'Samoa' => 'WS',
  'San Marino' => 'SM',
  'Sao Tome and Principe' => 'ST',
  'Saudi Arabia' => 'SA',
  'Senegal' => 'SN',
  'Serbia' => 'RS',
  'Seychelles' => 'SC',
  'Sierra Leone' => 'SL',
  'Singapore' => 'SG',
  'Slovakia' => 'SK',
  'Slovenia' => 'SI',
  'Solomon Islands' => 'SB',
  'Somalia' => 'SO',
  'South Africa' => 'ZA',
  'South Georgia and the South Sandwich Islands' => 'GS',
  'Spain' => 'ES',
  'Sri Lanka' => 'LK',
  'Sudan' => 'SD',
  'Suriname' => 'SR',
  'Svalbard and Jan Mayen' => 'SJ',
  'Swaziland' => 'SZ',
  'Sweden' => 'SE',
  'Switzerland' => 'CH',
  'Syrian Arab Republic' => 'SY',
  'Taiwan, Province of China' => 'TW',
  'Tajikistan' => 'TJ',
  'Tanzania, United Republic of' => 'TZ',
  'Thailand' => 'TH',
  'Timor-Leste' => 'TL',
  'Togo' => 'TG',
  'Tokelau' => 'TK',
  'Tonga' => 'TO',
  'Trinidad and Tobago' => 'TT',
  'Tunisia' => 'TN',
  'Turkey' => 'TR',
  'Turkmenistan' => 'TM',
  'Turks and Caicos Islands' => 'TC',
  'Tuvalu' => 'TV',
  'Uganda' => 'UG',
  'Ukraine' => 'UA',
  'United Arab Emirates' => 'AE',
  'United Kingdom' => 'GB',
  'United States' => 'US',
  'United States Minor Outlying Islands' => 'UM',
  'Uruguay' => 'UY',
  'Uzbekistan' => 'UZ',
  'Vanuatu' => 'VU',
  'Venezuela, Bolivarian Republic of' => 'VE',
  'Viet Nam' => 'VN',
  'Virgin Islands, British' => 'VG',
  'Virgin Islands, U.S.' => 'VI',
  'Wallis and Futuna' => 'WF',
  'Western Sahara' => 'EH',
  'Yemen' => 'YE',
  'Zambia' => 'ZM',
  'Zimbabwe' => 'ZW'
}.freeze
@@stdin_lines =

The contents of anything piped to stdin, split into lines. See stdin

nil

Class Method Summary collapse

Class Method Details

.apiJSS::APIConnection Also known as: api_connection, connection, active_connection

The currently active JSS::APIConnection instance.

Returns:



1052
1053
1054
# File 'lib/jss/api_connection.rb', line 1052

def self.api
  @api ||= APIConnection.new name: :default
end

.api_object_class(name) ⇒ Class

Given a name, singular or plural, of a JSS::APIObject subclass as a String or Symbol (e.g. :computer/'computers'), return the class itself (e.g. JSS::Computer) The available names are the RSRC_LIST_KEY and RSRC_OBJECT_KEY values for each APIObject subclass.

Parameters:

  • name (String, Symbol)

    The name of a JSS::APIObject subclass, singluar or plural

Returns:

  • (Class)

    The class

Raises:



429
430
431
432
433
434
# File 'lib/jss/utility.rb', line 429

def self.api_object_class(name)
  klass = api_object_names[name.downcase.to_sym]
  raise JSS::InvalidDataError, "Unknown API Object Class: #{name}" unless klass

  klass
end

.api_object_namesHash

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 JSS::Computer and both :policy and :policies are keys for JSS::Policy, and so on.

Returns:

  • (Hash)

    APIObject subclass names to Classes



448
449
450
451
452
453
454
455
456
457
458
459
460
461
# File 'lib/jss/utility.rb', line 448

def self.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? JSS::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>

Parameters:

  • element (#to_s)

    an element_name like :foo

  • list (Array<#to_s>)

    an Array of element content such as [“bar”, :morefoo]

Returns:

  • (Array<REXML::Element>)

Raises:



491
492
493
494
495
496
497
498
499
500
# File 'lib/jss/utility.rb', line 491

def self.array_to_rexml_array(element, list)
  raise JSS::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

.country_code_match(str) ⇒ Hash

Return the names and codes containing a given string (case insentitive).

Parameters:

  • str (String)

    the string to look for, must be >=2 chars long

Returns:

  • (Hash)

    the country names => codes that contain the string.

Raises:

  • (ArgumentError)


36
37
38
39
40
41
# File 'lib/jss/api_object/app_store_country_codes.rb', line 36

def self.country_code_match(str)
  raise ArgumentError, 'Match string must be at least 2 characters long' if str.size < 2

  str = str.to_s.upcase
  APP_STORE_COUNTRY_CODES.select { |n, c| n.upcase.include?(str) || c.include?(str) }
end

.dbMysql

Returns The mysql database available through the DBConnection.instance.

Returns:

  • (Mysql)

    The mysql database available through the DBConnection.instance



293
294
295
# File 'lib/jss/db_connection.rb', line 293

def self.db
  DB_CNX.db
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.

Parameters:

  • Set (Symbol)

    devmode :on or :off

Returns:

  • (Boolean)

    The new state of devmode



660
661
662
# File 'lib/jss/utility.rb', line 660

def self.devmode(setting)
  @devmode = setting == :on
end

.devmode?Boolean

is devmode currently on?

Returns:

  • (Boolean)


668
669
670
# File 'lib/jss/utility.rb', line 668

def self.devmode?
  @devmode
end

.epoch_to_time(epoch) ⇒ Time?

Converts JSS epoch (unix epoch + milliseconds) to a Ruby Time object

Parameters:

  • epoch (String, Integer, nil)

Returns:

  • (Time, nil)

    nil is returned if epoch is nil, 0 or an empty String.



410
411
412
413
414
# File 'lib/jss/utility.rb', line 410

def self.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.

* & => &amp;
* " => &quot;
* < => &lt;
* > => &gt;
* ' => &apos;

Parameters:

  • string (String)

    the string to make xml-compliant.

Returns:

  • (String)

    the xml-compliant string



474
475
476
# File 'lib/jss/utility.rb', line 474

def self.escape_xml(string)
  string.gsub(/&/, '&amp;').gsub(/\"/, '&quot;').gsub(/>/, '&gt;').gsub(/</, '&lt;').gsub(/'/, '&apos;')
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

Examples:

JSS.expand_min_os ">=10.9.4" # => returns this array
 # ["10.9.4",
 #  "10.9.5",
 #  "10.10.x"
 #  ...
 #  "10.16.x",
 #  "11.x",
 #  "12.x",
 #  ...
 #  "20.x"]

Parameters:

  • min_os (String)

    the mimimum OS version to expand, e.g. “>=10.9.4” or “11.1”

Returns:

  • (Array)

    Nearly all potential OS versions from the minimum to 20.12.10



116
117
118
119
120
121
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
# File 'lib/jss/utility.rb', line 116

def self.expand_min_os(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
      if minor.to_i < 15
        ((minor.to_i + 1)..15).each { |v| ok_oses << "10.#{v}.x" }
      end

      # 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
  if ['11', '11.x', '11.x.x', '11.0', '11.0.0'].include?(min_os) && !ok_oses.include?('10.16')
    ok_oses << '10.16'
  end

  # 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

Examples:

my_hash = {:foo => "bar", :baz => :morefoo}
xml = JSS.hash_to_rexml_array(my_hash)
xml.each{|x| puts x }

<foo>bar</foo>
<baz>morefoo</baz>

Parameters:

  • hash (Hash{#to_s => #to_s})

    the Hash to convert

Returns:

  • (Array<REXML::Element>)

    the Array of REXML elements.

Raises:



518
519
520
521
522
523
524
525
526
527
528
# File 'lib/jss/utility.rb', line 518

def self.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

.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

Examples:

comps = [{:id=>2,:name=>'kimchi'},{:id=>5,:name=>'mantis'}]
xml = JSS.item_list_to_rexml_list(:computers, :computer , comps, :name)
puts xml
# output manually formatted for clarity. No newlines in the real xml string
<computers>
  <computer>
    <name>kimchi</name>
  </computer>
  <computer>
    <name>mantis</name>
  </computer>
</computers>

# if content is :id, then, eg. <name>kimchi</name> would be <id>2</id>

Parameters:

  • list_element (#to_s)

    the name of the XML element that contains the list.

  • item_element (#to_s)

    the name of each XML element in the list,

  • item_list (Array<Hash>)

    an Array of Hashes each with a :name or :id key.

  • content (Symbol) (defaults to: :name)

    which hash key should be used as the content of if list item? Defaults to :name

Returns:

  • (REXML::Element)

    the item list as REXML



562
563
564
565
566
567
568
# File 'lib/jss/utility.rb', line 562

def self.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

.new_api_connection(args = {}) ⇒ APIConnection Also known as: new_connection, new_api

Create a new APIConnection object and use it for all future API calls. If connection options are provided, they are passed to the connect method immediately, otherwise JSS.api.connect must be called before attemting to use the connection.

Parameters:

Returns:



1019
1020
1021
1022
# File 'lib/jss/api_connection.rb', line 1019

def self.new_api_connection(args = {})
  args[:name] ||= :default
  @api = APIConnection.new args
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.

Parameters:

  • requirement (String, Array)

    The os requirement list, a comma-seprated string or array of strings of allows OSes. e.g. 10.7, 10.8.5 or 10.9.x

  • processor (String)

    the os to check, defaults to the os of the current machine.

Returns:

  • (Boolean)

    can this pkg be installed with the processor given?



250
251
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
# File 'lib/jss/utility.rb', line 250

def self.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_datetime(a_datetime) ⇒ Object

Deprecated - to be eventually removed in favor of the more-appropriately named JSS::parse_time

See Also:

  • parse_time


400
401
402
# File 'lib/jss/utility.rb', line 400

def self.parse_datetime(a_datetime)
  parse_time(a_datetime)
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

Parameters:

  • version (String)

    a JSS version number from the API

Returns:

  • (Hash{Symbol => String, Gem::Version})

    the parsed version data.

Raises:



587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
# File 'lib/jss/utility.rb', line 587

def self.parse_jss_version(version)
  major, second_part, *_rest = version.split('.')
  raise JSS::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.

Parameters:

  • plist (Pathname, String)

    the plist XML, or the path to a plist file

  • symbol_keys (Boolean) (defaults to: false)

    should any Hash keys in the result be converted into Symbols rather than remain as Strings?

Returns:

  • (Object)

    the parsed plist as a ruby hash,array, etc.



325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/jss/utility.rb', line 325

def self.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 JSS::MissingDataError, "No such file: #{plist}" unless plist.file?

  CFPropertyList.native_types(CFPropertyList::List.new(file: plist).value, symbol_keys)
end

.parse_time(a_datetime) ⇒ Time?

Converts anything that responds to #to_s to a Time, or nil

Return nil if the item is nil, 0 or an empty String.

Otherwise the item converted to a string, and parsed with DateTime.parse. It is then examined to see if it has a UTC offset. If not, the local offset is applied, then the DateTime is converted to a Time.

Parameters:

  • a_datetime (#to_s)

    The thing to convert to a time.

Returns:

  • (Time, nil)

    nil is returned if a_datetime is nil, 0 or an empty String.



379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# File 'lib/jss/utility.rb', line 379

def self.parse_time(a_datetime)
  return nil if NIL_DATES.include? a_datetime

  the_dt = DateTime.parse(a_datetime.to_s)

  # The microseconds in DateTimes are stored as a fraction of a day.
  # Convert them to an integer of microseconds
  usec = (the_dt.sec_fraction * 60 * 60 * 24 * (10**6)).to_i

  # if the UTC offset of the datetime is zero, make a new one with the correct local offset
  # (which might also be zero if we happen to be in GMT)
  the_dt = DateTime.new(the_dt.year, the_dt.month, the_dt.day, the_dt.hour, the_dt.min, the_dt.sec, JSS::TIME_ZONE_OFFSET) if the_dt.offset.zero?
  # now convert it to a Time and return it
  Time.at the_dt.strftime('%s').to_i, usec
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.

Parameters:

  • requirement (String)

    The processor requirement. either 'ppc', 'x86', or some variation on “none”, nil, or empty

  • processor (String) (defaults to: nil)

    the processor to check, defaults to the processor of the current machine. Any flavor of intel

    is (i486, i386, x86-64, etc) is treated as "x86"
    

Returns:

  • (Boolean)

    can this pkg be installed with the processor given?



230
231
232
233
234
235
# File 'lib/jss/utility.rb', line 230

def self.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.

Parameters:

  • message (String)

    the prompt message to display

Returns:

  • (String)

    the text typed by the user



639
640
641
642
643
644
645
646
647
648
649
650
# File 'lib/jss/utility.rb', line 639

def self.prompt_for_password(message)
  begin
    $stdin.reopen '/dev/tty' unless $stdin.tty?
    $stderr.print "#{message} "
    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

Parameters:

  • line (Integer) (defaults to: 0)

    which line of stdin is being retrieved. The default is zero (0) which returns all of stdin as a single string.

Returns:

  • (String, nil)

    the requested ling of stdin, or nil if it doesn't exist.



624
625
626
627
628
629
630
631
# File 'lib/jss/utility.rb', line 624

def self.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?.

Returns:

  • (Boolean)

    is this code running as root?



610
611
612
# File 'lib/jss/utility.rb', line 610

def self.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.

Examples:

JSS.to_s_and_a "foo, bar, baz" # Hash => {:stringform => "foo, bar, baz", :arrayform => ["foo", "bar", "baz"]}

JSS.to_s_and_a ["foo", "bar", "baz"] # Hash => {:stringform => "foo, bar, baz", :arrayform => ["foo", "bar", "baz"]}

Parameters:

  • somedata (String, Array)

    the data to parse, of either class,

Returns:

  • (Hash{:stringform => String, :arrayform => Array})

    the data as both comma-separated String and Array



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/jss/utility.rb', line 296

def self.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 JSS::InvalidDataError, 'Input must be a comma-separated String or an Array of Strings'
  end # case
  { stringform: valstr, arrayform: valarr }
end

.use_api_connection(connection) ⇒ APIConnection Also known as: use_api, use_connection, activate_connection

Switch the connection used for all API interactions to the one provided. See APIConnection for details and examples of using multiple connections

Parameters:

  • connection (APIConnection)

    The APIConnection to use for future API calls. If omitted, use the default connection created when ruby-jss was loaded (which may or may not yet be connected)

Returns:



1034
1035
1036
1037
1038
# File 'lib/jss/api_connection.rb', line 1034

def self.use_api_connection(connection)
  raise 'API connections must be instances of JSS::APIConnection' unless connection.is_a? JSS::APIConnection

  @api = connection
end

.use_default_connectionvoid

This method returns an undefined value.

Make the default connection (Stored in JSS::API) active



1044
1045
1046
# File 'lib/jss/api_connection.rb', line 1044

def self.use_default_connection
  use_api_connection @api
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

Parameters:

  • data (Object)

    the data to be converted, usually a Hash

Returns:

  • (String)

    the object converted into an XML plist



360
361
362
363
364
365
# File 'lib/jss/utility.rb', line 360

def self.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