예제 #1
0
def RunPostflight(runtype):
    """Run the full postflight script."""
    # support enterprise/802.1x user-context wifi auth.
    # don't bother to perform postflight and exit OK immediately since there's no
    # network connection.
    if runtype == 'logoutinstall':
        sys.exit(0)


# Ensure MSU is installed to /Applications
    if not IsAppInPlace():
        flight_common.RepairClient()

    url = flight_common.GetServerURL()
    client = mac_client.SimianAuthClient(
        flight_common.GetClientIdentifier('auto')['uuid'], hostname=url)
    client.SetAuthToken(flight_common.GetAuth1Token())

    # read SecureConfig.plist.
    plist = munkicommon.SecureManagedInstallsPreferences()

    # Post client_id to server.
    client_id = flight_common.GetClientIdentifier(runtype)
    pkgs_to_install, apple_updates_to_install = (
        flight_common.GetRemainingPackagesToInstall())
    params = {
        'client_id': flight_common.DictToStr(client_id),
        'pkgs_to_install': pkgs_to_install,
        'apple_updates_to_install': apple_updates_to_install,
    }
    client.PostReport('postflight', params)

    # Report installs/etc to server.
    flight_common.UploadAllManagedInstallReports(
        client, client_id.get('on_corp', 'None'))

    if not client.LogoutAuthToken():
        logging.error('Logout failed')

    # expire auth token and remove cookie from plist.
    RemoveAuthTokenHeaderFromPlist(plist)

    # Delete the temp dir that munkicommon creates on import.
    munkicommon.cleanUpTmpDir()

    # Mark successful run by writing to last success file.
    NoteLastSuccess()

    logging.debug('Postflight completed successfully.')
def main():
    optparser = optparse.OptionParser()
    optparser.add_option('-r',
                         '--reason',
                         dest='reason',
                         default='Unknown',
                         help='Reason for brokenness.')
    optparser.add_option('-d',
                         '--detail-file',
                         dest='detail_file',
                         help='File with error details.')
    options, _ = optparser.parse_args()

    detail_parts = []

    if options.detail_file:
        try:
            detail_parts.append('Failure detail:\n%s' %
                                open(options.detail_file, 'r').read())
        except IOError as e:
            detail_parts.append('Could not read detail file %r:\n%s' %
                                (options.detail_file, e))

    return_code, stdout, stderr = flight_common.Exec(['facter', '-p'],
                                                     timeout=60,
                                                     waitfor=0.5)
    facter_parts = [
        'Facter Return Code: %s' % return_code,
        'Facter StdOut:\n%s' % stdout,
    ]
    if stderr:
        facter_parts.append('Facter StdErr:\n%s' % stderr)
    detail_parts.append('\n\n'.join(facter_parts))

    details = ('\n\n' + ('*' * 60) + '\n\n').join(
        [part.strip() for part in detail_parts])
    params = {'details': details, 'reason': options.reason}

    url = flight_common.GetServerURL()
    c = client.SimianAuthClient(
        flight_common.GetClientIdentifier('auto')['uuid'], hostname=url)
    c.GetAuthToken()
    c.PostReport('broken_client', params)
    print 'Reported broken client to server.'
예제 #3
0
파일: preflight.py 프로젝트: runt18/simian
def LoginToServer(secure_config, client_id, user_settings, client_exit=None):
  """Sets an auth token cookie header to a plist object.

  Args:
    secure_config: secure Preferences object.
    client_id: dict client identifier.
    user_settings: dict of user settings.
    client_exit: optional, default None, str explaining why the client is
      requesting to exit its execution.
  Returns:
    Tuple of a SimianAuthClient, a dict containing feedback from the server.
  """
  headers = []

  # Preserve all non-Cookie and non-ClientID headers that may exist.
  if munkicommon.ADDITIONAL_HTTP_HEADERS_KEY in secure_config:
    for header in secure_config[munkicommon.ADDITIONAL_HTTP_HEADERS_KEY]:
      if (not header.startswith('Cookie:') and
          not header.startswith(MUNKI_CLIENT_ID_HEADER_KEY)):
        headers.append(header)

  client_id_str = flight_common.DictToStr(client_id)

  if user_settings:
    try:
      user_settings_str = urllib.quote(
          json.dumps(flight_common.Flatten(user_settings)))
    except TypeError:
      logging.error(
          'preflight cannot flatten user_settings: %s', str(user_settings))
      user_settings_str = ''
  else:
    user_settings_str = ''

  client_params = {
      '_report_type': 'preflight',
      'client_id': client_id_str,
      'user_settings': user_settings_str,
      'json': '1',
  }
  if client_exit:
    client_params['client_exit'] = client_exit

  client_params = urllib.urlencode(client_params)

  url = flight_common.GetServerURL()
  client = mac_client.SimianAuthClient(hostname=url)
  token = client.GetAuthToken()
  response = client.PostReportBody(client_params)
  feedback = {}
  try:
    feedback = json.loads(response[len(JSON_PREFIX):])
  except ValueError:
    logging.exception('Error parsing JSON')

  if not isinstance(feedback, dict):
    logging.error(
        'preflight failure getting feedback dict (%r)', feedback)

  # Add the Cookie and client id to the headers.
  headers.append('User-Agent: gzip')  # enforce GFE compression
  headers.append('Cookie: %s' % token)
  headers.append('%s: %s' % (MUNKI_CLIENT_ID_HEADER_KEY, client_id_str))
  # Replace AdditionalHttpHeaders with the new headers list.
  secure_config[munkicommon.ADDITIONAL_HTTP_HEADERS_KEY] = headers

  return client, feedback
예제 #4
0
파일: simianauth.py 프로젝트: smusa/simian
 def GetSimianClientInstance(self, *args, **kwargs):
     """Returns an instance of the Simian client to use within this CLI."""
     return client.SimianAuthClient(*args, **kwargs)