def geolocate(): networks = [] if platform == 'darwin': from Foundation import NSBundle, objc b = NSBundle.bundleWithPath_( objc.pathForFramework( '/System/Library/Frameworks/CoreWLAN.framework')) if b is None: raise SystemError( 'Unable to load wireless bundle. Maybe its not supported?') b.load() cwi = b.classNamed_('CWInterface') if cwi is None: raise SystemError('Unable to load CWInterface.') iface = cwi.interface() if iface is None or not iface: raise SystemError('Unable to load wireless interface.') networks = map( lambda x: { 'ssid': x.ssid(), 'mac': x.bssid(), 'ss': x.rssi() }, iface.scanForNetworksWithParameters_error_(None, None)) # iface.release() # b.unload() else: raise NotImplementedError('This module is still under development.') return _geolocate(networks)
def pathForResource(resourceName, extension, path = None): if path and len(path) > 10: bundlePath = path[:path.find("/Contents/Resources/")] bundle = NSBundle.bundleWithPath_(bundlePath) return bundle.pathForResource_ofType_(resourceName, extension) else: raise("Please supply path")
def pathForResource(resourceName, extension, path=None): if path and len(path) > 10: bundlePath = path[:path.find("/Contents/Resources/")] bundle = NSBundle.bundleWithPath_(bundlePath) return bundle.pathForResource_ofType_(resourceName, extension) else: raise("Please supply path")
def is_beta(): """Returns whether the version of macOS is a beta release or not. The SUAdminInstallController class and the isSeedBuild method may not be available on all installations of macOS. This works with macOS >= 10.13 if the necessary import and framework paths are available to the running python. Returns: None, False or True. It is None when the necessary import is not found or macOS < 10.13. Otherwise, it returns True if the installed OS is a beta release and False if not. """ if NSBundle is None: return None parts = get_os_version_number().split('.') if len(parts) < 2: return None major, minor = int(parts[0]), int(parts[1]) if major < 10 or (major == 10 and minor < 13): return None SoftwareUpdate = NSBundle.bundleWithPath_( '/System/Library/PrivateFrameworks/SoftwareUpdate.framework') SUAdminInstallController = SoftwareUpdate.classNamed_( 'SUAdminInstallController') return bool(SUAdminInstallController.isSeedBuild())
def get_bundle_id(app_name): '''Given an app_name, get the bundle_id''' from AppKit import NSWorkspace from Foundation import NSBundle app_path = NSWorkspace.sharedWorkspace().fullPathForApplication_(app_name) if app_path: return NSBundle.bundleWithPath_(app_path).bundleIdentifier() return None
def packageIncludesKSDiff(path): bundle = NSBundle.bundleWithPath_(path) version = bundle.objectForInfoDictionaryKey_("CFBundleShortVersionString") if StrictVersion(version) >= StrictVersion('2.0.0'): return False else: return True
def get_bundle_id(app_name): '''Given an app_name, get the bundle_id''' from AppKit import NSWorkspace from Foundation import NSBundle app_path = NSWorkspace.sharedWorkspace( ).fullPathForApplication_(app_name) if app_path: return NSBundle.bundleWithPath_(app_path).bundleIdentifier() return None
def supportsMergeAtPath(path): bundle = NSBundle.bundleWithPath_(path) version = bundle.objectForInfoDictionaryKey_("CFBundleShortVersionString") if StrictVersion(version) >= StrictVersion('2.0.0'): return True else: return False
def pluginBundle(pluginName): """ Deprecated: use currentBundle() Return the main bundle for the named plugin. This should be used only after it has been registered with registerPlugin """ warnings.warn("Deprecated: use currentBundle()", DeprecationWarning) from Foundation import NSBundle return NSBundle.bundleWithPath_(_PLUGINS[pluginName])
def os_x_set_system_ui_mode(mode, option): # noinspection PyUnresolvedReferences import objc # noinspection PyUnresolvedReferences from Foundation import NSBundle bundle = NSBundle.bundleWithPath_( "/System/Library/Frameworks/Carbon.framework") objc.loadBundleFunctions( bundle, globals(), (("SetSystemUIMode", b"III", ""),)) # noinspection PyUnresolvedReferences SetSystemUIMode(mode, option)
def os_x_set_system_ui_mode(mode, option): # noinspection PyUnresolvedReferences import objc # noinspection PyUnresolvedReferences from Foundation import NSBundle bundle = NSBundle.bundleWithPath_( "/System/Library/Frameworks/Carbon.framework") objc.loadBundleFunctions(bundle, globals(), (("SetSystemUIMode", b"III", ""), )) # noinspection PyUnresolvedReferences SetSystemUIMode(mode, option)
def _load(g=globals()): import objc from Foundation import NSBundle OSErr = objc._C_SHT def S(*args): return ''.join(args) FUNCTIONS = [ (u'LSGetApplicationForInfo', 'sII@Io^{FSRef=[80C]}o^@'), ] bndl = NSBundle.bundleWithPath_(objc.pathForFramework('/System/Library/Frameworks/ApplicationServices.framework')) objc.loadBundleFunctions(bndl, g, FUNCTIONS)
def timezone_lookup(): """Force a timezone lookup right now""" TZPP = NSBundle.bundleWithPath_("/System/Library/PreferencePanes/" "DateAndTime.prefPane/Contents/" "Resources/TimeZone.prefPane") TimeZonePref = TZPP.classNamed_('TimeZonePref') ATZAdminPrefererences = TZPP.classNamed_('ATZAdminPrefererences') atzap = ATZAdminPrefererences.defaultPreferences() pref = TimeZonePref.alloc().init() atzap.addObserver_forKeyPath_options_context_(pref, "enabled", 0, 0) result = pref._startAutoTimeZoneDaemon_(0x1) # If this is not set to 1 then AutoTimezone still isn't enabled. # This additional preference check makes this script work with 10.12 if pref.isTimeZoneAutomatic() is not 1: return False return True
def _load(g=globals()): import objc from Foundation import NSBundle OSErr = objc._C_SHT def S(*args): return ''.join(args) FUNCTIONS = [ (u'LSGetApplicationForInfo', 'sII@Io^{FSRef=[80C]}o^@'), ] bndl = NSBundle.bundleWithPath_( objc.pathForFramework( '/System/Library/Frameworks/ApplicationServices.framework')) objc.loadBundleFunctions(bndl, g, FUNCTIONS)
def libraryNameForSymbol(symbol): bndl = NSBundle.bundleWithPath_(u'/System/Library/Frameworks/System.framework') d = {} objc.loadBundleFunctions(bndl, d, FUNCTIONS) for (fn, sig) in FUNCTIONS: if fn not in d: raise ValueError("Couldn't find function %s" % (fn,)) symbol = b'_' + symbol if not d['NSIsSymbolNameDefined'](symbol): # symbol not defined return None sym = d['NSLookupAndBindSymbol'](symbol) if not sym: raise ValueError("Couldn't bind symbol %r" % (symbol,)) mod = d['NSModuleForSymbol'](sym) if not mod: raise ValueError("Couldn't find module for symbol %r" % (symbol,)) return d['NSLibraryNameForModule'](mod)
def libraryNameForSymbol(symbol): bndl = NSBundle.bundleWithPath_( "/System/Library/Frameworks/System.framework") d = {} objc.loadBundleFunctions(bndl, d, FUNCTIONS) for (fn, sig) in FUNCTIONS: if fn not in d: raise ValueError("Couldn't find function %s" % (fn, )) symbol = b"_" + symbol if not d["NSIsSymbolNameDefined"](symbol): # symbol not defined return None sym = d["NSLookupAndBindSymbol"](symbol) if not sym: raise ValueError("Couldn't bind symbol %r" % (symbol, )) mod = d["NSModuleForSymbol"](sym) if not mod: raise ValueError("Couldn't find module for symbol %r" % (symbol, )) return d["NSLibraryNameForModule"](mod)
def process(self): # Determine the bundle_id of the app path provided bundle = NSBundle.bundleWithPath_(self.path) if not bundle: raise ActionError( 'unable to locate the bundle id of the app path provided') bundle_id = bundle.bundleIdentifier() # The user is trying to change the default application for a content type if self.content_type: # Get the default bundle id for the specified content type default_bundle_id = LSCopyDefaultRoleHandlerForContentType( self.content_type, kLSRolesAll) if not default_bundle_id: raise ActionError( 'the content type provided could not be found') # The current default application matches the one requested if default_bundle_id.lower() == bundle_id.lower(): return self.ok() # Change the default application for the specified content type LSSetDefaultRoleHandlerForContentType(self.content_type, kLSRolesAll, bundle_id) return self.changed() # The user is trying to change the default application for a URL scheme else: # Get the default bundle id for the specified url scheme default_bundle_id = LSCopyDefaultHandlerForURLScheme( self.url_scheme) if not default_bundle_id: raise ActionError('the url scheme provided could not be found') # The current default application matches the one requested if default_bundle_id.lower() == bundle_id.lower(): return self.ok() # Change the default application for the specified url scheme LSSetDefaultHandlerForURLScheme(self.url_scheme, bundle_id) return self.changed()
def init(self): """ By default, toolbar.pdf will be your tool icon. Use this for any initializations you need. """ try: self = objc.super(SelectTool, self).init() self.name = 'My Select Tool' self.toolbarPosition = 100 self._icon = 'toolbar.pdf' self.keyboardShortcut = None self.generalContextMenus = () # Inspector dialog stuff # Initiate self.inspectorDialogView here in case of Vanilla dialog, # where inspectorDialogView is not defined at the class’s root. if not hasattr(self, 'inspectorDialogView'): self.inspectorDialogView = None if hasattr(self, 'settings'): self.settings() try: if hasattr(self, "__file__"): path = self.__file__() Bundle = NSBundle.bundleWithPath_(path[:path.rfind("Contents/Resources/")]) else: Bundle = NSBundle.bundleForClass_(NSClassFromString(self.className())) if self._icon is not None: self.tool_bar_image = Bundle.imageForResource_(self._icon) self.tool_bar_image.setTemplate_(True) # Makes the icon blend in with the toolbar. except: self.logError(traceback.format_exc()) if hasattr(self, 'start'): self.start() return self except: self.logError(traceback.format_exc()) return objc.nil
def init(self): """ By default, toolbar.pdf will be your tool icon. Use this for any initializations you need. """ try: self = objc.super(SelectTool, self).init() self.name = 'My Select Tool' self.toolbarPosition = 100 self._icon = 'toolbar.pdf' self.keyboardShortcut = None self.generalContextMenus = () # Inspector dialog stuff # Initiate self.inspectorDialogView here in case of Vanilla dialog, # where inspectorDialogView is not defined at the class’s root. if not hasattr(self, 'inspectorDialogView'): self.inspectorDialogView = None if hasattr(self, 'settings'): self.settings() try: if hasattr(self, "__file__"): path = self.__file__() Bundle = NSBundle.bundleWithPath_(path[:path.rfind("Contents/Resources/")]) else: Bundle = NSBundle.bundleForClass_(NSClassFromString(self.className())); if self._icon != None: self.tool_bar_image = Bundle.imageForResource_(self._icon) self.tool_bar_image.setTemplate_(True) # Makes the icon blend in with the toolbar. except: self.logError(traceback.format_exc()) if hasattr(self, 'start'): self.start() return self except: self.logError(traceback.format_exc()) return objc.nil
def domains_handled_by_plugins(): '''Returns a list of profile PayloadTypes handled by plugins''' xpcservices = ('/System/Library/PrivateFrameworks/' 'ConfigurationProfiles.framework/XPCServices') domain_list = [] for item in os.listdir(xpcservices): info_plist = os.path.join(xpcservices, item, "Contents/Info.plist") try: info = FoundationPlist.readPlist(info_plist) domains_supported = info.get('ProfileDomainService', {}).get('DomainsSupported') if domains_supported: domain_list.extend(domains_supported) except FoundationPlist.FoundationPlistException: pass plugin_dirs = ( '/System/Library/CoreServices/ManagedClient.app/Contents/PlugIns', '/System/Library/ConfigurationProfiles/PlugIns', ) ignore_plugins = ( 'mcx.profileDomainPlugin', 'loginwindow.profileDomainPlugin', ) for plugin_dir in plugin_dirs: for item in os.listdir(plugin_dir): if item in ignore_plugins: continue if not item.endswith('.profileDomainPlugin'): continue plugin_path = os.path.join(plugin_dir, item) plugin = NSBundle.bundleWithPath_(plugin_path) principal_class = plugin.principalClass() domains_supported = list( principal_class.new().pdp_pluginDomainsSupported()) if domains_supported: domain_list.extend(domains_supported) return domain_list
def LoadNib(self, nibname, path = None): if path and len(path) > 10: bundlePath = path[:path.find("/Contents/Resources/")] bundle = NSBundle.bundleWithPath_(bundlePath) nib = NSNib.alloc().initWithNibNamed_bundle_(nibname, bundle) if not nib: self.logError("Error loading nib for Class: %s" % self.__class__.__name__) result = nib.instantiateWithOwner_topLevelObjects_(self, None) try: error = bool(result[0]) except: error = bool(result) # in 10.9, the result is a bool if not error: self.logError("Error instantiating nib for Class: %s" % self.__class__.__name__) else: try: self.topLevelObjects = result[1] except: pass else: if not NSBundle.loadNibNamed_owner_(nibname, self): self.logError("Error loading %s.nib." % nibname)
def LoadNib(self, nibname, path=None): if path and len(path) > 10: bundlePath = path[:path.find("/Contents/Resources/")] bundle = NSBundle.bundleWithPath_(bundlePath) nib = NSNib.alloc().initWithNibNamed_bundle_(nibname, bundle) if not nib: self.logError("Error loading nib for Class: %s" % self.__class__.__name__) result = nib.instantiateWithOwner_topLevelObjects_(self, None) try: error = bool(result[0]) except: error = bool(result) # in 10.9, the result is a bool if not error: self.logError("Error instantiating nib for Class: %s" % self.__class__.__name__) else: try: self.topLevelObjects = result[1] except: pass else: if not NSBundle.loadNibNamed_owner_(nibname, self): self.logError("Error loading %s.nib." % nibname)
def WMEnable(name="Python"): if not isinstance(name, bytes): name = name.encode("utf8") mainBundle = NSBundle.mainBundle() bPath = os.path.split(os.path.split(os.path.split( sys.executable)[0])[0])[0] if mainBundle.bundlePath() == bPath: return True bndl = NSBundle.bundleWithPath_( objc.pathForFramework( "/System/Library/Frameworks/ApplicationServices.framework")) if bndl is None: print("ApplicationServices missing", file=sys.stderr) return False d = {} objc.loadBundleFunctions(bndl, d, FUNCTIONS) for (fn, _sig) in FUNCTIONS: if fn not in d: print("Missing", fn, file=sys.stderr) return False err, psn = d["GetCurrentProcess"](None) if err: print("GetCurrentProcess", (err, psn), file=sys.stderr) return False err = d["CPSSetProcessName"](psn, name) if err: print("CPSSetProcessName", (err, psn), file=sys.stderr) return False err = d["CPSEnableForegroundOperation"](psn) if err: print("CPSEnableForegroundOperation", (err, psn), file=sys.stderr) return False err = d["SetFrontProcess"](psn) if err: print("SetFrontProcess", (err, psn), file=sys.stderr) return False return True
def geolocate(): networks = [] if platform == 'darwin': from Foundation import NSBundle, objc b = NSBundle.bundleWithPath_(objc.pathForFramework('/System/Library/Frameworks/CoreWLAN.framework')) if b is None: raise SystemError('Unable to load wireless bundle. Maybe its not supported?') b.load() cwi = b.classNamed_('CWInterface') if cwi is None: raise SystemError('Unable to load CWInterface.') iface = cwi.interface() if iface is None or not iface: raise SystemError('Unable to load wireless interface.') networks = map( lambda x: {'ssid':x.ssid(),'mac':x.bssid(),'ss':x.rssi()}, iface.scanForNetworksWithParameters_error_(None, None) ) # iface.release() # b.unload() else: raise NotImplementedError('This module is still under development.') return _geolocate(networks)
def init(self): """ Do all initializing here. """ try: # Settings, default values self.name = 'My File Format' self.icon = 'ExportIcon' self.toolbarPosition = 100 if hasattr(self, 'settings'): self.settings() # Dialog stuff # Initiate empty self.dialog here in case of Vanilla dialog, # where .dialog is not defined at the class’s root. if not hasattr(self, 'dialog'): self.dialog = None if hasattr(self, "__file__"): path = self.__file__() thisBundle = NSBundle.bundleWithPath_(path[:path.rfind("Contents/Resources/")]) else: thisBundle = NSBundle.bundleForClass_(NSClassFromString(self.className())) self.toolbarIcon = NSImage.alloc().initWithContentsOfFile_(thisBundle.pathForImageResource_(self.icon)) # Using self.toolbarIconName() instead of self.icon to # make sure registered NSImage name is unique self.toolbarIcon.setName_(self.toolbarIconName()) if hasattr(self, 'start'): self.start() except: self.logError(traceback.format_exc()) return self
# Tested on 10.11 # Assumes your network is in a state to actually do the discovery and that you have # automatic timezone discovery enabled in Date & Time and Location services enabled # (Generally this means wifi enabled on your device and network stack is up) # For enabling location services and auto, check Allister's work here: # https://gist.github.com/arubdesu/b72585771a9f606ad800 from Foundation import NSBundle TZPP = NSBundle.bundleWithPath_("/System/Library/PreferencePanes/DateAndTime.prefPane/Contents/Resources/TimeZone.prefPane") TimeZonePref = TZPP.classNamed_('TimeZonePref') ATZAdminPrefererences = TZPP.classNamed_('ATZAdminPrefererences') atzap = ATZAdminPrefererences.defaultPreferences() pref = TimeZonePref.alloc().init() atzap.addObserver_forKeyPath_options_context_(pref, "enabled", 0, 0) result = pref._startAutoTimeZoneDaemon_(0x1)
import objc import time from application.notification import IObserver, NotificationCenter from application.python import Null from zope.interface import implements from util import allocate_autorelease_pool, run_in_gui_thread from BlinkLogger import BlinkLogger from MediaStream import STREAM_CONNECTED, STREAM_IDLE, STREAM_FAILED from SIPManager import SIPManager bundle = NSBundle.bundleWithPath_(objc.pathForFramework('ApplicationServices.framework')) objc.loadBundleFunctions(bundle, globals(), [('CGEventSourceSecondsSinceLastEventType', 'diI')]) IDLE_TIME = 5 ALPHA = 1.0 class VideoControlPanel(NSWindowController): implements(IObserver) visible = False full_screen = True holdButton = objc.IBOutlet() hangupButton = objc.IBOutlet() chatButton = objc.IBOutlet() infoButton = objc.IBOutlet() muteButton = objc.IBOutlet()
from Foundation import NSLocale, NSBundle, NSClassFromString from multiprocessing import Pool from xml.etree import ElementTree from numbers import Number from subprocess import Popen, PIPE from ctypes import CDLL, c_uint, byref from datetime import datetime VERSION = "5.3" DISKUTIL = "/usr/sbin/diskutil" IATOOL = "Contents/MacOS/InstallAssistant" STARTOSINSTALL = "Contents/Resources/startosinstall" os.environ['__OS_INSTALL'] = "1" SeedingBundle = NSBundle.bundleWithPath_('/System/Library/PrivateFrameworks/Seeding.framework') functions = [ ('_stringForSeedProgram_', '@I'), ('_setSeedProgramPref', '@I'), ('_setCatalogForSeedProgram', '@I'), ('_setHelpFeedbackMenuEnabled', '@I'), ('_setSeedOptOutUIDisabled', '@I'), ('_createFeedbackAssistantSymlink','@'), ] objc.loadBundleFunctions(SeedingBundle, globals(), functions) # # Setup seed program data. #
import Quartz global lock_player global warn_player CoreBluetooth = NSBundle.bundleWithIdentifier_('com.apple.CoreBluetooth') _ = CoreBluetooth.load() CBCentralManager = NSClassFromString('CBCentralManager') constants = [ ('CBCentralManagerScanOptionAllowDuplicatesKey', '@'), ('CBAdvertisementDataManufacturerDataKey', '@'), ] objc.loadBundleVariables(CoreBluetooth, globals(), constants) Login = NSBundle.bundleWithPath_( '/System/Library/PrivateFrameworks/login.framework') functions = [ ('SACLockScreenImmediate', '@'), ] objc.loadBundleFunctions(Login, globals(), functions) # Prep the sound file lock_sound_file = NSURL.fileURLWithPath_(path_to_lock_sound) lock_player = AVAudioPlayer.alloc().initWithContentsOfURL_error_( lock_sound_file, None) lock_player.setNumberOfLoops_(0) # Prep the sound file warn_sound_file = NSURL.fileURLWithPath_(path_to_warn_sound) warn_player = AVAudioPlayer.alloc().initWithContentsOfURL_error_(
import os import sys import objc from Foundation import NSBundle, NSLog old_path = set(sys.path) old_modules = set(sys.modules) bndl = NSBundle.bundleWithPath_(os.path.abspath("dist/PyTestPlugin.pbplugin")) NSLog(f"currentBundle = {objc.currentBundle()!r}") PyTestPlugin = bndl.classNamed_("PyTestPlugin") NSLog(f"PyTestPlugin = {PyTestPlugin!r}") PyTestPlugin.alloc().init() NSLog(f"currentBundle = {objc.currentBundle()!r}") NSLog(f"paths changed: {set(sys.path) - old_path!r}") NSLog(f"new modules: {set(sys.modules) - old_modules!r}")
def ExtensionBundle(title): path = __file__ bundlePath = path[:path.find("/Contents/Resources/")] bundle = NSBundle.bundleWithPath_(bundlePath) return bundle
def main(): '''This function is very similar to our fix but instead of performing any systematic changes will read the information and report it to jamf as an extension attribute.''' eap8021x_bundle = NSBundle.bundleWithPath_( '/System/Library/PrivateFrameworks/EAP8021X.framework') # EAP Functions from @mosen's meap project (See above for link) eapol_functions = [ ('EAPOLClientConfigurationGetTypeID', 'Q'), ('EAPOLClientProfileGetTypeID', 'Q'), ('EAPOLClientItemIDGetTypeID', 'Q'), ('EAPOLClientConfigurationCreate', '^{EAPOLClientConfigurationRef=}^{__CFAllocator=}'), ('EAPOLClientProfileGetUserDefinedName', '@^{EAPOLClientProfileRef=}'), ('EAPOLClientConfigurationGetSystemProfile', '^{EAPOLClientProfileRef=}' '^{EAPOLClientConfigurationRef=}@'), ('EAPOLClientConfigurationSetSystemProfile', 'Z^{EAPOLClientConfigurationRef=}@' '^{EAPOLClientProfileRef=}'), ('EAPOLClientConfigurationSave', 'Z^{EAPOLClientConfigurationRef=}') ] objc.loadBundleFunctions(eap8021x_bundle, globals(), eapol_functions) # CF Types to be loaded also from @mosen's meap project cf_types = [ ('EAPOLClientConfigurationRef', '^{EAPOLClientConfigurationRef=}', EAPOLClientConfigurationGetTypeID()), ('EAPOLClientProfileRef', '^{EAPOLClientProfileRef=}', EAPOLClientProfileGetTypeID()), ('EAPOLClientItemIDRef', '^{EAPOLClientItemIDRef=}', EAPOLClientItemIDGetTypeID()), ] for item in cf_types: objc.registerCFSignature(*item) # Define blank list to be used to gather EAPOL information on # Ethernet interfaces interface_list = [] prefs = SCPreferencesCreate(None, "python", None) services = SCNetworkServiceCopyAll(prefs) # Poll through the interfaces and make a list of the true Ethernet # adapters on the system for interface in ethernet_services(services): interface_list.append(SCNetworkInterfaceGetBSDName(interface)) # For loop to iterate through our Ethernet adapters and determine if they # have the system profile we are looking for and apply it to any other # Ethernet interfaces that don't have it applied. Change "Ethernet(COE)" # to whatever your 802.1x profile is called in Network Preferences. # Default in jamf is sadly "Network" for ethernet in interface_list: cfg = EAPOLClientConfigurationCreate(None) look_for_cfg = EAPOLClientConfigurationGetSystemProfile(cfg, ethernet) if look_for_cfg is not None: if EAPOLClientProfileGetUserDefinedName( look_for_cfg) == 'Ethernet(COE)': for ethernet in interface_list: if EAPOLClientConfigurationGetSystemProfile( cfg, ethernet) == look_for_cfg: continue else: EAPOLClientConfigurationSetSystemProfile( cfg, ethernet, look_for_cfg) EAPOLClientConfigurationSave(cfg)
#!/usr/bin/env python """Via https://github.com/allfro/sploitego/blob/master/src/sploitego/webtools/geolocate.py""" from log import log AIRBEARS = "AirBears" from Foundation import NSBundle, objc CoreWLANBundle = NSBundle.bundleWithPath_(objc.pathForFramework('/System/Library/Frameworks/CoreWLAN.framework')) if CoreWLANBundle is None: raise SystemError("Unable to load wireless bundle. Maybe it's not supported?") # CoreWLAN is 10.6+ only CoreWLANBundle.load() def has_airbears(): connected = get_connected_wireless() if connected is None: return False log("Active connected network: " + connected) return AIRBEARS == connected def get_connected_wireless(): # I _think_ I might have to call [CWInterface interface] every time... CWInterface = CoreWLANBundle.classNamed_('CWInterface') if CWInterface is None: raise SystemError('Unable to load CWInterface.') # Possibly < 10.6? default_interface = CWInterface.interface() if default_interface is None or not default_interface: # raise SystemError('Unable to load wireless interface.') # If it's not there, don't complain
import objc from CoreFoundation import CFUUIDCreateFromString from Foundation import NSBundle bndl = NSBundle.bundleWithPath_(objc.pathForFramework('/System/Library/Frameworks/ApplicationServices.framework/' 'Versions/A/Frameworks/HIServices.framework/' 'Versions/A/HIServices')) objc.loadBundleFunctions(bndl, globals(), [ (u'DesktopPictureCopyDisplayForSpace', b'^{__CFDictionary=}Ii^{__CFString=}'), (u'DesktopPictureSetDisplayForSpace', b'vI^{__CFDictionary=}ii^{__CFString=}'), ]) bndl = NSBundle.bundleWithPath_(objc.pathForFramework('/System/Library/Frameworks/CoreGraphics.framework/Versions/A/' 'CoreGraphics')) objc.loadBundleFunctions(bndl, globals(), [ (u'_CGSDefaultConnection', b'i'), (u'CGSCopyManagedDisplaySpaces', b'^{__CFArray=}i', '', {'retval': {'already_retained': True}}), (u'CGMainDisplayID', b'I'), (u'CGSGetDisplayForUUID', b'I^{__CFUUID=}'), ]) class OSXSpace(object): def __init__(self, uuid, display_uuid, managed_space_id, id64, type, wsid): self.uuid = uuid self.display_uuid = display_uuid self.managed_space_id = managed_space_id self.id64 = id64 self.type = type self.wsid = wsid
from AVFoundation import ( AVCaptureDeviceInput, AVCaptureVideoDataOutput, AVCaptureDevice, AVCaptureSession, AVCaptureVideoPreviewLayer, AVCaptureStillImageOutput, AVCaptureSessionPresetHigh, AVLayerVideoGravityResizeAspectFill, AVMediaTypeVideo, AVMediaTypeMuxed, AVVideoCodecJPEG, AVVideoCodecKey) import objc from Quartz.QuartzCore import kCALayerHeightSizable, kCALayerWidthSizable from Quartz.CoreGraphics import kCGColorBlack, CGColorGetConstantColor from Quartz import CVBufferRetain, NSCIImageRep, CIImage, CVBufferRelease from Quartz.CoreVideo import kCVPixelBufferPixelFormatTypeKey from Quartz.CoreVideo import kCVPixelFormatType_32BGRA bundle = NSBundle.bundleWithPath_(objc.pathForFramework('CoreMedia.framework')) objc.loadBundleFunctions(bundle, globals(), [('CMSampleBufferGetImageBuffer', b'@@')]) import objc import re from BlinkLogger import BlinkLogger from util import run_in_gui_thread from sipsimple.core import Engine from sipsimple.application import SIPApplication from sipsimple.configuration.settings import SIPSimpleSettings from sipsimple.threading.green import run_in_green_thread from application.notification import NotificationCenter, IObserver, NotificationData
# Note: # The marketing information embedded in the ServerInformation.framework is not the same as what # About This Mac displays - there are differences. # # For example: # ServerInformation: 15" MacBook Pro with Retina display (Mid 2015) # About This Mac: MacBook Pro (Retina, 15-inch, Mid 2015) # # About This Mac will actually hit the internet API to perform the lookup, # and then saves it locally for future use. from Foundation import NSBundle import xml.etree.ElementTree as ET import urllib2 ServerInformation = NSBundle.bundleWithPath_('/System/Library/PrivateFrameworks/ServerInformation.framework') ServerCompatibility = NSBundle.bundleWithPath_('/System/Library/PrivateFrameworks/ServerCompatibility.framework') ServerInformationComputerModelInfo = ServerInformation.classNamed_('ServerInformationComputerModelInfo') SVCSystemInfo = ServerCompatibility.classNamed_('SVCSystemInfo') info = SVCSystemInfo.currentSystemInfo() extended_info = ServerInformationComputerModelInfo.attributesForModelIdentifier_(info.computerModelIdentifier()) if extended_info: # We don't have to hit the internet API, we have some marketing knowledge marketing_name = extended_info['marketingModel'] else: # Sadly we'll have to reach out API = urllib2.urlopen('http://support-sp.apple.com/sp/product?cc=' + info.serialNumber()[-4:]) marketing_name = ET.fromstring(API.read()).find('configCode').text
#!/usr/bin/env python # Allow user to locate Stata application, and write bundle identifier to # TextMate preferences import os import subprocess import plistlib import StringIO from Foundation import NSBundle dialog_cmd = [os.environ['DIALOG'],'filepanel', '--title','Locate Stata Application', '--prompt','Use With TextMate', '--message','Please locate the Stata application you wish to use with TextMate', '--defaultDirectory','/Applications', '--allowsMultipleSelection','0', '--canChooseDirectories','0', '--allowedFileTypes','app'] plist = subprocess.check_output(dialog_cmd) app = plistlib.readPlist(StringIO.StringIO(plist)) path = app.get('path') if path: bundle_id = NSBundle.bundleWithPath_(path).bundleIdentifier() subprocess.call(['defaults','write','%s' % (os.environ['TM_APP_IDENTIFIER'],), 'stataBundleIdentifier',bundle_id]) print(bundle_id)
# coding: utf-8 # https://gist.github.com/bmw1821/de3ab9cb8bb4b7719571 # https://forum.omz-software.com/topic/2726/pythonista-replaykit from objc_util import * from Foundation import NSBundle NSBundle.bundleWithPath_('/System/Library/Frameworks/ReplayKit.framework').load() RPScreenRecorder = ObjCClass('RPScreenRecorder')
# coding: utf-8 # https://gist.github.com/bmw1821/de3ab9cb8bb4b7719571 # https://forum.omz-software.com/topic/2726/pythonista-replaykit from objc_util import * from Foundation import NSBundle NSBundle.bundleWithPath_( '/System/Library/Frameworks/ReplayKit.framework').load() RPScreenRecorder = ObjCClass('RPScreenRecorder')
# Hat tip to https://github.com/anders/pwgen for various initial documentation # For an alternative method, check out: # https://gist.github.com/pudquick/8d3dedc337161b187a8a1c9564c83463 import objc from Foundation import NSBundle, NSMutableArray, NSString SecurityFoundation = NSBundle.bundleWithPath_( '/System/Library/Frameworks/SecurityFoundation.framework') success = SecurityFoundation.load() PASS_MIN_LENGTH = 4 PASS_MAX_LENGTH = 1024 PASS_MAX_REQUEST = 15 algorithm = { 'memorable': 0, 'random': 1, 'letters': 2, # FIPS-181 compliant 'alphanumeric': 3, 'numbers': 4, } SFPWAContextRef = objc.createOpaquePointerType("SFPWAContextRef", b"^{_SFPWAContext=}", None) functions = [ ('SFPWAPolicyCopyDefault', '@'), ('SFPWAContextCreateWithDefaults', '^{_SFPWAContext=}'), ('SFPWAContextCreate', '^{_SFPWAContext=}'), ('SFPWAContextLoadDictionaries', 'v^{_SFPWAContext=}^{__CFArray=}I'),
#!/usr/bin/python #ref: https://gist.github.com/pudquick/3ff4278c609ce223ebb4fc300c5edd0f # Hat tip to https://github.com/anders/pwgen for various initial documentation # For an alternative method, check out: # https://gist.github.com/pudquick/8d3dedc337161b187a8a1c9564c83463 import objc from Foundation import NSBundle, NSMutableArray, NSString SecurityFoundation = NSBundle.bundleWithPath_('/System/Library/Frameworks/SecurityFoundation.framework') success = SecurityFoundation.load() PASS_MIN_LENGTH = 4 PASS_MAX_LENGTH = 1024 PASS_MAX_REQUEST = 15 algorithm = { 'memorable': 0, 'random': 1, 'letters': 2, # FIPS-181 compliant 'alphanumeric': 3, 'numbers': 4, } SFPWAContextRef = objc.createOpaquePointerType("SFPWAContextRef", b"^{_SFPWAContext=}", None) functions = [ ('SFPWAPolicyCopyDefault', '@'), ('SFPWAContextCreateWithDefaults', '^{_SFPWAContext=}'), ('SFPWAContextCreate', '^{_SFPWAContext=}'),
def bundleid(app_path): """Return bundle ID for application at ``app_path``""" from Foundation import NSBundle bundle = NSBundle.bundleWithPath_(app_path) return bundle.bundleIdentifier()
kUIModeContentSuppressed = 1 kUIModeContentHidden = 2 kUIModeAllSuppressed = 4 kUIModeAllHidden = 3 kUIOptionAutoShowMenuBar = 1 << 0 kUIOptionDisableAppleMenu = 1 << 2 kUIOptionDisableProcessSwitch = 1 << 3 kUIOptionDisableForceQuit = 1 << 4 kUIOptionDisableSessionTerminate = 1 << 5 kUIOptionDisableHide = 1 << 6 # wrapped function import sys sys.path.append('/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python') sys.path.append('/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC') import objc from Foundation import NSBundle bundle = NSBundle.bundleWithPath_('/System/Library/Frameworks/Carbon.framework') objc.loadBundleFunctions(bundle, globals(), ( ('SetSystemUIMode', 'III', " Sets the presentation mode for system-provided user interface elements."), )) options = ( kUIOptionDisableAppleMenu #| kUIOptionDisableProcessSwitch | kUIOptionDisableForceQuit | kUIOptionDisableSessionTerminate | kUIOptionDisableHide ) SetSystemUIMode(kUIModeAllHidden, options) sys.path = sys.path[:-2]
#!/usr/bin/env python # Nicolas Seriot # 2015-04-11 import argparse import os import time from Foundation import NSBundle, NSClassFromString, NSDictionary, NSURL success = NSBundle.bundleWithPath_("/System/Library/PrivateFrameworks/PhotoLibraryPrivate.framework/Versions/A/Frameworks/PAImaging.framework").load() assert success == True CIImage = NSClassFromString("CIImage") assert CIImage CIFilter = NSClassFromString("CIFilter") assert CIFilter NSBitmapImageRep = NSClassFromString("NSBitmapImageRep") assert NSBitmapImageRep IPAPhotoAdjustmentStackSerializer_v10 = NSClassFromString("IPAPhotoAdjustmentStackSerializer_v10") assert IPAPhotoAdjustmentStackSerializer_v10 ipaPASS = IPAPhotoAdjustmentStackSerializer_v10.alloc().init() def apply_cifilter_with_name(filter_name, orientation, in_path, out_path, dry_run=False): print "-- in: ", in_path
#!/usr/bin/python #ref: https://gist.github.com/pudquick/8d3dedc337161b187a8a1c9564c83463 # For an alternative method, check out: # https://gist.github.com/pudquick/3ff4278c609ce223ebb4fc300c5edd0f from Foundation import NSBundle, NSClassFromString SafariShared = NSBundle.bundleWithPath_('/System/Library/PrivateFrameworks/SafariShared.framework') loaded = SafariShared.load() WBSPasswordGeneration = NSClassFromString('WBSPasswordGeneration') CKRecord = NSClassFromString('CKRecord') def generate_password(requirements=None): rec = CKRecord.alloc().initWithRecordType_('pudquick_passwordgen') if requirements is not None: # dictionary of values to set passed in rec.setValuesForKeysWithDictionary_(requirements) password = WBSPasswordGeneration.generatedPasswordMatchingRequirements_(rec) # Do a little cleanup, since we don't actually want to save any CloudKit records del rec return password # Example usage # >>> generate_password() # u'hhs-o7X-kaZ-ngw' # Returns an iCloud Keychain suggested password in the style seen here: # https://support.apple.com/library/APPLE/APPLECARE_ALLGEOS/Product_Help/en_US/PUBLIC_USERS/PL124/S0700_CloudKeychain.png # Alternatively, you can define various keys in a dictionary and pass it in # >>> r = { # >>> 'PasswordMinLength': 20,
# This was all run from user space # I haven't tested it with root # ... but it didn't prompt for any permissions under userspace ^_^ # Tested on 10.11.5 import objc from Foundation import NSBundle EAP8021X_bundle = NSBundle.bundleWithPath_('/System/Library/PrivateFrameworks/EAP8021X.framework') Security_bundle = NSBundle.bundleWithIdentifier_('com.apple.security') kEAPOLClientDomainUser = 1 kEAPOLClientDomainSystem = 3 E_functions = [ ('EAPOLClientConfigurationCopyProfiles', '@@'), ('EAPOLClientConfigurationCopyAllLoginWindowProfiles', '@@'), ('EAPOLClientConfigurationCopyAllSystemProfiles', '@@'), ('EAPOLClientConfigurationCreate', '@^@'), ('EAPOLClientConfigurationGetProfileWithID', '@@@'), ('EAPOLClientItemIDCopyIdentity', '@@i'), ('EAPOLClientItemIDCreateWithProfile', '@@'), ('EAPOLClientProfileGetAuthenticationProperties', '@@'), ('EAPOLClientProfileGetUserDefinedName', '@@'), ('EAPOLClientProfileGetWLANSSIDAndSecurityType', '@@o^@'), ('EAPOLClientProfileGetID', '@@'), ('EAPOLControlCopyStateAndStatus', 'i*o^io^@'), ('EAPSecCertificateCopyAttributesDictionary', '@@'), ('EAPSecCertificateCopyUserNameString', '@@'), ] S_functions = [
# Note: # The marketing information embedded in the ServerInformation.framework is not the same as what # About This Mac displays - there are differences. # # For example: # ServerInformation: 15" MacBook Pro with Retina display (Mid 2015) # About This Mac: MacBook Pro (Retina, 15-inch, Mid 2015) # # About This Mac will actually hit the internet API to perform the lookup, # and then saves it locally for future use. from Foundation import NSBundle import xml.etree.ElementTree as ET import urllib2 ServerInformation = NSBundle.bundleWithPath_( '/System/Library/PrivateFrameworks/ServerInformation.framework') ServerCompatibility = NSBundle.bundleWithPath_( '/System/Library/PrivateFrameworks/ServerCompatibility.framework') ServerInformationComputerModelInfo = ServerInformation.classNamed_( 'ServerInformationComputerModelInfo') SVCSystemInfo = ServerCompatibility.classNamed_('SVCSystemInfo') info = SVCSystemInfo.currentSystemInfo() extended_info = ServerInformationComputerModelInfo.attributesForModelIdentifier_( info.computerModelIdentifier()) if extended_info: # We don't have to hit the internet API, we have some marketing knowledge marketing_name = extended_info['marketingModel'] else:
#!/usr/bin/python #ref: https://gist.github.com/pudquick/8d3dedc337161b187a8a1c9564c83463 # For an alternative method, check out: # https://gist.github.com/pudquick/3ff4278c609ce223ebb4fc300c5edd0f from Foundation import NSBundle, NSClassFromString SafariShared = NSBundle.bundleWithPath_( '/System/Library/PrivateFrameworks/SafariShared.framework') loaded = SafariShared.load() WBSPasswordGeneration = NSClassFromString('WBSPasswordGeneration') CKRecord = NSClassFromString('CKRecord') def generate_password(requirements=None): rec = CKRecord.alloc().initWithRecordType_('pudquick_passwordgen') if requirements is not None: # dictionary of values to set passed in rec.setValuesForKeysWithDictionary_(requirements) password = WBSPasswordGeneration.generatedPasswordMatchingRequirements_( rec) # Do a little cleanup, since we don't actually want to save any CloudKit records del rec return password # Example usage # >>> generate_password() # u'hhs-o7X-kaZ-ngw' # Returns an iCloud Keychain suggested password in the style seen here: # https://support.apple.com/library/APPLE/APPLECARE_ALLGEOS/Product_Help/en_US/PUBLIC_USERS/PL124/S0700_CloudKeychain.png