コード例 #1
0
def sniff_wifi():
    if plat == "OSX":
        # bridge to objective c(apple stuff)
        objc.loadBundle(
            "CoreWLAN", bundle_path="/System/Library/Frameworks/CoreWLAN.framework", module_globals=globals()
        )

        for iname in CWInterface.interfaceNames():
            interface = CWInterface.interfaceWithName_(iname)
            wifi_parameters = (
                "Interface:      %s, SSID:           %s, Transmit Rate:  %s, Transmit Power: %s, RSSI:           %s"
                % (iname, interface.ssid(), interface.transmitRate(), interface.transmitPower(), interface.rssi())
            )
    elif plat == "LINUX":
        interface = Wireless("wlan0")

        # Link Quality, Signal Level and Noise Level line
        wifi_parameters = "Interface:      %s, SSID:           %s, Transmit Rate:  %s, Transmit Power: %s" % (
            "wlan0",
            interface.getEssid(),
            interface.getBitrate(),
            interface.getTXPower(),
        )

    # record wifi parameters
    print wifi_parameters
    open(channels_file, "a").write(wifi_parameters + "\n")
コード例 #2
0
 def load_growl(self):
     if self.loaded_growl.isSet():
         return
     try:
         TRACE('Loading Growl...')
         pool = NSAutoreleasePool.alloc().init()
         if self.GrowlApplicationBridge is None:
             bundle_path = '%s/Growl.framework' % get_frameworks_dir()
             env = {}
             objc.loadBundle('GrowlApplicationBridge', env, bundle_path=bundle_path)
             self.GrowlApplicationBridge = env['GrowlApplicationBridge']
             installed = self.GrowlApplicationBridge.isGrowlInstalled()
             running = self.GrowlApplicationBridge.isGrowlRunning()
             TRACE('Growl is installed? %r; Growl is running? %r', installed, running)
         if running:
             TRACE('Initializing Growl Delegate')
             self.GrowlApplicationBridge.setGrowlDelegate_(self)
         else:
             return
     except Exception:
         unhandled_exc_handler()
         self.growl_had_problems = True
         TRACE('Growl had problems, tossing ability to notify out the window')
     else:
         self.growl_had_problems = False
         self.growlIsReady()
コード例 #3
0
 def __init__(self, master):
     try:
         objc.loadBundle('Sparkle', globals(), join(dirname(sys.executable), os.pardir, 'Frameworks', 'Sparkle.framework'))
         self.updater = SUUpdater.sharedUpdater()
     except:
         # can't load framework - not frozen or not included in app bundle?
         self.updater = None
コード例 #4
0
 def wifi_connect(self):
     try:
         objc.loadBundle(
             'CoreWLAN',
             bundle_path='/System/Library/Frameworks/CoreWLAN.framework',
             module_globals=globals())
         iface = CWInterface.interface(
         )  # CWInterface is provided by MacOS system not in python module, get from CoreWLAN obect-C
         networks, scan_error = iface.scanForNetworksWithName_error_(
             self.ssid, None)
         network = networks.anyObject()
         connect_success, connect_error = iface.associateToNetwork_password_error_(
             network, self.password, None)
         if connect_success:
             print('Successful to connect wifi ' + self.ssid)
             hostname = socket.gethostname()
             IPAddr = socket.gethostbyname(hostname)
             #print('curl --insecure --data "show_video_id:=BBB|http://' + IPAddr + ':8080/spain.mp4" -H "Content-Type:application/json" -X POST https://192.168.43.1:8080/command')
             a = os.popen(
                 'curl --insecure --data "show_video_id:=BBB|http://' +
                 IPAddr +
                 ':8080/spain.mp4" -H "Content-Type:application/json" -X POST https://192.168.43.1:8080/command'
             ).readlines()
             print(a)
         if connect_error:
             print('!!!! failed to connect wifi "' + self.ssid + '"')
     except Exception as e:
         print(e)
コード例 #5
0
ファイル: f5vpn-login.py プロジェクト: mrBuG/f5vpn-login
def OSX_get_a_certificate():
    # This function is @#$@#@#$ retarded. Its only point is to extract a single
    # cert from the OSX trusted cert store, so I can put it in a file, so I give
    # that file to Python's SSL module (which gives it to OpenSSL), which then
    # basically ignores that I'm explicitly telling it to only trust that one
    # certificate, and uses all the certificates in OSX's trusted cert store,
    # anyways. But it forces me to give it a file with a cert in it regardless
    # of the fact that it's planning to use the **entire cert store**
    # regardless of what I actually ask for...sigh. Why???
    import objc, tempfile
    global OSX_cert_tempfile

    # ALSO, wtf doesn't Security.framework already have python wrappers like the
    # rest of OSX's frameworks?? Just make up a minimal wrapper here...
    Security=types.ModuleType('Security')
    objc.loadBundle(Security.__name__, Security.__dict__,
                    bundle_identifier="com.apple.security")
    objc.parseBridgeSupport('''<signatures version="0.9"><depends_on path="/System/Library/Frameworks/CoreFoundation.framework"/><enum name="kSecFormatX509Cert" value="9"/><enum name="kSecItemPemArmour" value="1"/><function name="SecTrustCopyAnchorCertificates"><arg type="o^@"/><retval type="l"/></function><function name="SecKeychainItemExport"><arg type="@"/><arg type="I"/><arg type="I"/><arg type="^{?=II^v@@@II}"/><arg type="o^@"/><retval type="l"/></function></signatures>''', Security.__dict__, Security.__name__)

    res, certs = Security.SecTrustCopyAnchorCertificates(None)

    if res == 0:
        for cert in certs:
            res, data = Security.SecKeychainItemExport(
                cert,
                Security.kSecFormatX509Cert, Security.kSecItemPemArmour, None, None)
            if res == 0:
                OSX_cert_tempfile = tempfile.NamedTemporaryFile()
                OSX_cert_tempfile.write(str(buffer(data)))
                OSX_cert_tempfile.flush()
                return OSX_cert_tempfile.name

    return None
コード例 #6
0
ファイル: app.py プロジェクト: x-raizor/plotdevice
    def applicationDidFinishLaunching_(self, note):
        mm=NSApp().mainMenu()

        # disable the start-dictation item in the edit menu
        edmenu = mm.itemAtIndex_(2).submenu()
        for it in edmenu.itemArray():
            action = it.action()
            if action in (NSSelectorFromString("startDictation:"), ):
                edmenu.removeItem_(it)

        # add a hidden item to the menus that can be triggered internally by the editor
        for menu in mm.itemArray()[2:5]:
            flicker = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Flash This Menu', None, '')
            flicker.setEnabled_(True)
            flicker.setHidden_(True)
            menu.submenu().insertItem_atIndex_(flicker,0)

        # If the sparkle framework was installed in our bundle, init an updater
        self.sparkle = None
        sparkle_path = bundle_path(fmwk='Sparkle')
        if os.path.exists(sparkle_path):
            objc.loadBundle('Sparkle', globals(), bundle_path=sparkle_path)
            self.sparkle = objc.lookUpClass('SUUpdater').sharedUpdater()
            self.updatesMenu.setTarget_(self.sparkle)
            self.updatesMenu.setAction_("checkForUpdates:")
            self.updatesMenu.setHidden_(False)
コード例 #7
0
ファイル: update.py プロジェクト: Marginal/EliteOCR
 def __init__(self, window):
     try:
         objc.loadBundle('Sparkle', globals(), join(dirname(sys.executable), os.pardir, 'Frameworks', 'Sparkle.framework'))
         self.updater = SUUpdater.sharedUpdater()
     except:
         # can't load framework - not frozen or not included in app bundle?
         self.updater = None
コード例 #8
0
ファイル: f5vpn-login.py プロジェクト: mgrubb/f5vpn-login
def OSX_get_a_certificate():
    # This function is @#$@#@#$ retarded. Its only point is to extract a single
    # cert from the OSX trusted cert store, so I can put it in a file, so I give
    # that file to Python's SSL module (which gives it to OpenSSL), which then
    # basically ignores that I'm explicitly telling it to only trust that one
    # certificate, and uses all the certificates in OSX's trusted cert store,
    # anyways. But it forces me to give it a file with a cert in it regardless
    # of the fact that it's planning to use the **entire cert store**
    # regardless of what I actually ask for...sigh. Why???
    import objc, tempfile
    global OSX_cert_tempfile

    # ALSO, wtf doesn't Security.framework already have python wrappers like the
    # rest of OSX's frameworks?? Just make up a minimal wrapper here...
    Security=types.ModuleType('Security')
    objc.loadBundle(Security.__name__, Security.__dict__,
                    bundle_identifier="com.apple.security")
    objc.parseBridgeSupport('''<signatures version="0.9"><depends_on path="/System/Library/Frameworks/CoreFoundation.framework"/><enum name="kSecFormatX509Cert" value="9"/><enum name="kSecItemPemArmour" value="1"/><function name="SecTrustCopyAnchorCertificates"><arg type="o^@"/><retval type="l"/></function><function name="SecKeychainItemExport"><arg type="@"/><arg type="I"/><arg type="I"/><arg type="^{?=II^v@@@II}"/><arg type="o^@"/><retval type="l"/></function></signatures>''', Security.__dict__, Security.__name__)

    res, certs = Security.SecTrustCopyAnchorCertificates(None)

    if res == 0:
        for cert in certs:
            res, data = Security.SecKeychainItemExport(
                cert,
                Security.kSecFormatX509Cert, Security.kSecItemPemArmour, None, None)
            if res == 0:
                OSX_cert_tempfile = tempfile.NamedTemporaryFile()
                OSX_cert_tempfile.write(str(buffer(data)))
                OSX_cert_tempfile.flush()
                return OSX_cert_tempfile.name

    return None
コード例 #9
0
    def __init__(self, tkroot: 'tk.Tk' = None, provider: str = 'internal'):
        """
        :param tkroot: reference to the root window of the GUI
        :param provider: 'internal' or other string if not
        """
        self.root: 'tk.Tk' = tkroot
        self.provider: str = provider
        self.thread: threading.Thread = None

        if self.use_internal():
            return

        if sys.platform == 'win32':
            import ctypes

            try:
                self.updater = ctypes.cdll.WinSparkle

                # Set the appcast URL
                self.updater.win_sparkle_set_appcast_url(update_feed.encode())

                # Set the appversion *without* build metadata, as WinSparkle
                # doesn't do proper Semantic Version checks.
                # NB: It 'accidentally' supports pre-release due to how it
                # splits and compares strings:
                # <https://github.com/vslavik/winsparkle/issues/214>
                self.updater.win_sparkle_set_app_build_version(
                    appversion_nobuild)

                # set up shutdown callback
                global root
                root = tkroot
                self.callback_t = ctypes.CFUNCTYPE(None)  # keep reference
                self.callback_fn = self.callback_t(self.shutdown_request)
                self.updater.win_sparkle_set_shutdown_request_callback(
                    self.callback_fn)

                # Get WinSparkle running
                self.updater.win_sparkle_init()

            except Exception as ex:
                print_exc()
                self.updater = None

            return

        if sys.platform == 'darwin':
            import objc
            try:
                objc.loadBundle(
                    'Sparkle', globals(),
                    join(dirname(sys.executable), os.pardir, 'Frameworks',
                         'Sparkle.framework'))
                self.updater = SUUpdater.sharedUpdater()
            except:
                # can't load framework - not frozen or not included in app bundle?
                print_exc()
                self.updater = None
コード例 #10
0
ファイル: update.py プロジェクト: tandyuk/EDMarketConnector
 def __init__(self, master):
     try:
         objc.loadBundle(
             "Sparkle", globals(), join(dirname(sys.executable), os.pardir, "Frameworks", "Sparkle.framework")
         )
         self.updater = SUUpdater.sharedUpdater()
     except:
         # can't load framework - not frozen or not included in app bundle?
         self.updater = None
コード例 #11
0
def connect_to_wifi_network(network_name, network_pass):
    objc.loadBundle(
        'CoreWLAN',
        bundle_path='/System/Library/Frameworks/CoreWLAN.framework',
        module_globals=globals())
    iface = CWInterface.interface()
    networks, error = iface.scanForNetworksWithName_error_(network_name, None)
    network = networks.anyObject()
    success, error = iface.associateToNetwork_password_error_(
        network, network_pass, None)
コード例 #12
0
ファイル: tk.py プロジェクト: PixmSecurity/sparkle-try
 def check_for_updates(self):
     sparkle_path = pathForFramework(self.SPARKLE_PATH)
     loadBundle('Sparkle', self.objc_namespace, bundle_path=sparkle_path)
     sparkle = self.objc_namespace['SUUpdater'].sharedUpdater()
     #sparkle.setAutomaticallyChecksForUpdates_(True)
     #sparkle.setAutomaticallyDownloadsUpdates_(True)
     NSURL = self.objc_namespace['NSURL']
     sparkle.setFeedURL_(NSURL.URLWithString_(self.APPCAST_URL))
     sparkle.checkForUpdateInformation()
     sparkle.checkForUpdatesInBackground()
     print "Check for updates in background"
コード例 #13
0
ファイル: macupdate.py プロジェクト: deflektor/EliteOCR
 def init(self):
     self = objc.super(Delegate, self).init()
     try:
         objc.loadBundle('Sparkle', globals(), join(dirname(sys.executable), os.pardir, 'Frameworks', 'Sparkle.framework'))
         self.updater = SUUpdater.sharedUpdater()
         self.updater.setDelegate_(self)
     except:
         # can't load framework - not frozen or not included in app bundle?
         self.updater = None
     self.infocallback = None
     return self
コード例 #14
0
    def init(self):
        self = super(SparkleUpdater, self).init()

        # Load Sparkle framework.
        bundle_path = os.path.join(
            NSBundle.mainBundle().privateFrameworksPath(), 'Sparkle.framework')
        objc.loadBundle('Sparkle', globals(), bundle_path=bundle_path)

        self.sparkle = SUUpdater.sharedUpdater()
        self.sparkle.setDelegate_(self)
        return self
コード例 #15
0
    def init(self):
        self = super(Growler, self).init()
        self.name = 'UpShot'
        objc.loadBundle('GrowlApplicationBridge', globals(),
                        bundle_path=objc.pathForFramework(os.path.join(
                            NSBundle.mainBundle().resourcePath(),
                            'Growl.framework')))

        self._growl = GrowlApplicationBridge
        self._growl.setGrowlDelegate_(self)
        self._callback = lambda ctx: None
        return self
コード例 #16
0
ファイル: updater.py プロジェクト: fwenzel/upshot
    def init(self):
        self = super(SparkleUpdater, self).init()

        # Load Sparkle framework.
        bundle_path = os.path.join(
            NSBundle.mainBundle().privateFrameworksPath(),
            'Sparkle.framework')
        objc.loadBundle('Sparkle', globals(), bundle_path=bundle_path)

        self.sparkle = SUUpdater.sharedUpdater()
        self.sparkle.setDelegate_(self)
        return self
コード例 #17
0
ファイル: notifications.py プロジェクト: fwenzel/upshot
    def init(self):
        self = super(Growler, self).init()
        self.name = 'UpShot'
        objc.loadBundle(
            'GrowlApplicationBridge', globals(), bundle_path=os.path.join(
                NSBundle.mainBundle().privateFrameworksPath(),
                'Growl.framework'))

        self._growl = GrowlApplicationBridge
        self._growl.setGrowlDelegate_(self)

        return self
コード例 #18
0
ファイル: utils.py プロジェクト: rayleyva/upshot
def auto_update():
    """Run Sparkle auto-updating."""
    NSLog('Checking upshot.it for updates...')

    # Load Sparkle framework.
    base_path = os.path.join(os.path.dirname(os.getcwd()), 'Frameworks')
    bundle_path = os.path.abspath(os.path.join(os.getcwd(), 'Sparkle.framework'))
    NSLog(bundle_path)
    objc.loadBundle('Sparkle', globals(), bundle_path=bundle_path)

    # Instantiate a sparkle updater and check for updates.
    sparkle_updater = SUUpdater.alloc().init()
    sparkle_updater.checkForUpdates_(NSApplication.sharedApplication())
コード例 #19
0
ファイル: notifications.py プロジェクト: n0nick/upshot
    def init(self):
        self = super(Growler, self).init()
        self.name = "UpShot"
        objc.loadBundle(
            "GrowlApplicationBridge",
            globals(),
            bundle_path=objc.pathForFramework(os.path.join(NSBundle.mainBundle().resourcePath(), "Growl.framework")),
        )

        self._growl = GrowlApplicationBridge
        self._growl.setGrowlDelegate_(self)
        self._callback = lambda ctx: None
        return self
コード例 #20
0
 def connectToWifi(self, data):
     wifiData = self.cleanWifiData(data)
     name = wifiData[0]
     password = wifiData[1]
     objc.loadBundle(
         "CoreWLAN",
         bundle_path='/System/Library/Frameworks/CoreWLAN.framework',
         module_globals=globals())
     iface = CWInterface.interface()
     networks, error = iface.scanForNetworksWithName_error_(name, None)
     network = networks.anyObject()
     success, error = iface.associateToNetwork_password_error_(
         network, password, None)
コード例 #21
0
    def init(self):
        self = super(Growler, self).init()
        self.name = 'UpShot'
        objc.loadBundle('GrowlApplicationBridge',
                        globals(),
                        bundle_path=os.path.join(
                            NSBundle.mainBundle().privateFrameworksPath(),
                            'Growl.framework'))

        self._growl = GrowlApplicationBridge
        self._growl.setGrowlDelegate_(self)

        return self
コード例 #22
0
ファイル: bluetooth_sharing.py プロジェクト: ulte/unearth
def fact():
    '''Returns the current bluetooth sharing'''

    result = 'None'

    objc.loadBundle("IOBluetooth",
                    globals(),
                    bundle_path=objc.pathForFramework(
                        u'/System/Library/Frameworks/IOBluetooth.framework'))
    btprefs = IOBluetoothPreferences.alloc().init()
    result = bool(btprefs.fileTransferServicesEnabled())

    return {factoid: result}
コード例 #23
0
def set_status():
    """
	Reads a YML file named .slack_wifi_status.yml in the home directory of the user, and sets
	the slack status text and emoji according to the ssid entry in the yml file.  Example:
	---
	slack:
	  interface: en0
	  token: <oauth token from slack app>
	  url: https://slack.com/api/users.profile.set  
	  <commuting ssid name>:
	    status: On a Bus
	    icon: ":bus:"
	  <office ssid name>:
	    status: "In Office"
	    icon: ":office:"
	  <home ssid name>:
	    status: "WFH"
	    icon: ":house:"
	  Default:
	    status: ""
	    icon: ""
	...
	"""
    objc.loadBundle(
        'CoreWLAN',
        bundle_path='/System/Library/Frameworks/CoreWLAN.framework',
        module_globals=globals())

    home = expanduser("~")

    f = open('%s/.slack_wifi_status.yml' % home)
    config = yaml.safe_load(f)['slack']
    f.close()

    interfaceName = config['interface']
    en = CWInterface.interfaceWithName_(interfaceName)

    ssidConfig = config['Default']
    if en:
        ssid = en.ssid()
        if config[ssid]:
            ssidConfig = config[ssid]

    profile = {
        "status_text": ssidConfig['status'],
        "status_emoji": ssidConfig['icon']
    }
    js = json.dumps(profile)
    data = {"token": config['token'], "profile": js}

    response = requests.post(config['url'], data=data)
コード例 #24
0
 def init(self):
     self = objc.super(Delegate, self).init()
     try:
         objc.loadBundle(
             'Sparkle', globals(),
             join(dirname(sys.executable), os.pardir, 'Frameworks',
                  'Sparkle.framework'))
         self.updater = SUUpdater.sharedUpdater()
         self.updater.setDelegate_(self)
     except:
         # can't load framework - not frozen or not included in app bundle?
         self.updater = None
     self.infocallback = None
     return self
コード例 #25
0
def connect_to_wifi():
    if OS == "Darwin":
        import objc
        from objc import CWInterface

        objc.loadBundle(
            "CoreWLAN",
            bundle_path="/System/Library/Frameworks/CoreWLAN.framework",
            module_globals=globals(),
        )

        iface = CWInterface.interface()
        networks, error = iface.scanForNetworksWithName_error_(
            WIFI["network"], None)
        network = networks.anyObject()
        success, error = iface.associateToNetwork_password_error_(
            network, WIFI["password"], None)
        if error:
            print(f"[DEBUG] Couldn't connect to wifi '{WIFI['network']}'")
            return False
        else:
            print(f"[DEBUG] Connected to wifi '{WIFI['network']}'")
            return True

    elif OS == "Linux":
        import os

        cmd = "sudo iwlist wlp2s0 scan | grep -ioE 'ssid:\"(.*{}.*)'"
        result = list(os.popen(cmd.format(WIFI["SERVER"])))

        if "Device or resource busy" in result:
            return False
        else:
            ssid_list = [item.lstrip("SSID:").strip('"\n') for item in result]

        for name in ssid_list:
            cmd = (f"nmcli d wifi connect {name} "
                   f"password {WIFI['password']} "
                   f"iface {IFACE}")
            if os.system(cmd) != 0:
                print(f"[DEBUG] Couldn't connect to wifi '{WIFI['network']}'")
                return False
            else:
                print(f"[DEBUG] Connected to wifi '{WIFI['network']}'")
                return True

    else:
        print(f"[DEBUG] OS '{OS}' not supported for auto wifi connection")
        return False
コード例 #26
0
def openPort():
    global board
    objc.loadBundle(
        'ActiveWireBoard',
        globals(),
        bundle_path='/Library/Frameworks/ActiveWireBoard.framework')

    board = ActiveWireBoard.alloc()
    board.init()
    if board.openBoard() == False:
        print 'error opening board'
        raise EPLPulseEEGException("Couldn't open ActiveWire Board")

    if board.setBinaryPinDirections_("1111111111111111") == False:
        raise EPLPulseEEGException("Couldn't set pin directions")
    setState(False)  #force the board to always start low
コード例 #27
0
ファイル: wifi-scan.py プロジェクト: rkruk/osx-wifi-scanner
def scan(concrete_ssid=None):
    bundle_path = '/System/Library/Frameworks/CoreWLAN.framework'
    objc.loadBundle('CoreWLAN',
                    bundle_path=bundle_path,
                    module_globals=globals())

    iface = CWInterface.interface()
    networks = iface.scanForNetworksWithName_includeHidden_error_(
        concrete_ssid, True, None)
    return {
        i.ssid(): {
            'RSSI': i.rssiValue(),
            'BSSID': i.bssid()
        }
        for i in networks[0].allObjects() if i.ssid() is not None
    }
コード例 #28
0
ファイル: wifi_status.py プロジェクト: ulte/unearth
def fact():
    '''Returns the wifi power status of the Mac'''
    wifi_status = None
    objc.loadBundle('CoreWLAN',
                    bundle_path='/System/Library/Frameworks/CoreWLAN.framework',
                    module_globals=globals())

    wifi = CWInterface.interfaceNames()
    if wifi:
        for iname in wifi:
            interface = CWInterface.interfaceWithName_(iname)
        try:
            wifi_status = "On" if interface.powerOn() == 1 else "Off"
        except AttributeError:
            wifi_status = None
    return {factoid: wifi_status}
コード例 #29
0
 def checkUpdater(self):
     sparkle_path = bundle_path(fmwk="Sparkle")
     if os.path.exists(sparkle_path):
         # if this is a sparkle build, hook the ui elements up to the sharedUpdater
         objc.loadBundle("Sparkle", globals(), bundle_path=sparkle_path)
         sparkle = objc.lookUpClass("SUUpdater").sharedUpdater()
         self.updateDaily.bind_toObject_withKeyPath_options_("value", sparkle, "automaticallyChecksForUpdates", None)
         self.updateNow.setTarget_(sparkle)
         self.updateNow.setAction_("checkForUpdates:")
     else:
         # otherwise hide the Software Update box and resize the window
         updater_box = self.updateNow.superview().superview()
         updater_box.setHidden_(True)
         frame = self.window().frame()
         frame.size.height -= 52
         self.window().setFrame_display_(frame, True)
コード例 #30
0
def get_ssid():
    objc.loadBundle(
        "CoreWLAN",
        bundle_path="/System/Library/Frameworks/CoreWLAN.framework",
        module_globals=globals())

    interfaceNames = CWInterface.interfaceNames()
    if interfaceNames == None:
        return None

    ssid = None
    for iname in CWInterface.interfaceNames():
        interface = CWInterface.interfaceWithName_(iname)
        ssid = interface.ssid()

    return ssid
コード例 #31
0
ファイル: experiments.py プロジェクト: mgax/CocoaTile
def main():
    bundle_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                               'build/Release/CocoaTileDriver.bundle')

    CocoaTileDriver = objc.loadBundle("CocoaTileDriver", globals(), bundle_path)
    AccessibilityElement = CocoaTileDriver.classNamed_("AccessibilityElement")
    print AccessibilityElement.systemWide().attributeNames()
コード例 #32
0
def moveMouse(x, y):
    bndl = objc.loadBundle(
        'CoreGraphics', globals(),
        '/System/Library/Frameworks/ApplicationServices.framework')
    objc.loadBundleFunctions(bndl, globals(),
                             [('CGWarpMouseCursorPosition', 'v{CGPoint=ff}')])
    CGWarpMouseCursorPosition((x, y))
コード例 #33
0
def _load_objc_framework(framework_name):
    """Load an ObjC Framework bundle.

    :param str framework_name: framework_name (str): The name of the
        framework to load.

    :return: Generic class instance with public framework contents
        attached as attributes and methods.

    :rtype: object
    """
    log.trace('wifi._load_objc_framework: loading {}.'.format(framework_name))
    loaded_classes = dict()
    framework_bundle = objc.loadBundle(
        framework_name,
        bundle_path=os.path.dirname(ctypes.util.find_library(framework_name)),
        module_globals=loaded_classes)

    class AttributedFramework():
        pass

    framework = AttributedFramework()
    for name, loaded_class in loaded_classes.items():
        if not name.startswith('_'):
            setattr(framework, name, loaded_class)
    return framework
コード例 #34
0
 def checkUpdater(self):
     sparkle_path = bundle_path(fmwk='Sparkle')
     if os.path.exists(sparkle_path):
         # if this is a sparkle build, hook the ui elements up to the sharedUpdater
         objc.loadBundle('Sparkle', globals(), bundle_path=sparkle_path)
         sparkle = objc.lookUpClass('SUUpdater').sharedUpdater()
         self.updateDaily.bind_toObject_withKeyPath_options_(
             'value', sparkle, "automaticallyChecksForUpdates", None)
         self.updateNow.setTarget_(sparkle)
         self.updateNow.setAction_("checkForUpdates:")
     else:
         # otherwise hide the Software Update box and resize the window
         updater_box = self.updateNow.superview().superview()
         updater_box.setHidden_(True)
         frame = self.window().frame()
         frame.size.height -= 52
         self.window().setFrame_display_(frame, True)
コード例 #35
0
 def _load_objc_framework(self, f_name, f_path, class_whitelist):
     loaded = {}
     _ = objc.loadBundle(f_name, bundle_path=f_path, module_globals=loaded)
     desired = {}
     for x in class_whitelist:
         if x in loaded:
             desired[x] = loaded[x]
     return namedtuple("AttributedFramework", desired.keys())(**desired)
コード例 #36
0
def load_framework(framework_path):
    try:
        framework_name = path.basename(framework_path).split('.')[0]
        print('Loading %s from %s' % (framework_name, framework_path))
        return objc.loadBundle(framework_name, globals(), framework_path)
    except Exception as ex:
        print('Loading failed with exception: %s' % ex)
        return None
コード例 #37
0
def load_framework(framework_path):
    try:
        framework_name = path.basename(framework_path).split('.')[0]
        print('Loading %s from %s' % (framework_name, framework_path))
        return objc.loadBundle(framework_name, globals(), framework_path)
    except Exception as ex:
        print('Loading failed with exception: %s' % ex)
        return None
コード例 #38
0
def load_objc_framework(framework_name):
    # Utility function that loads a Framework bundle and creates a namedtuple where the attributes are the loaded classes from the Framework bundle
    loaded_classes = dict()
    framework_bundle = objc.loadBundle(
        framework_name,
        bundle_path=os.path.dirname(ctypes.util.find_library(framework_name)),
        module_globals=loaded_classes)
    return collections.namedtuple('AttributedFramework',
                                  loaded_classes.keys())(**loaded_classes)
コード例 #39
0
def _loadBundle(frameworkName, frameworkIdentifier, frameworkPath):
    if frameworkIdentifier is None:
        bundle = loadBundle(frameworkName, {},
                            bundle_path=frameworkPath,
                            scan_classes=False)

    else:
        try:
            bundle = loadBundle(frameworkName, {},
                                bundle_identifier=frameworkIdentifier,
                                scan_classes=False)

        except ImportError:
            bundle = loadBundle(frameworkName, {},
                                bundle_path=frameworkPath,
                                scan_classes=False)

    return bundle
コード例 #40
0
def sniff_wifi():
 if plat=='OSX':
  # bridge to objective c(apple stuff)
  objc.loadBundle('CoreWLAN',
                bundle_path='/System/Library/Frameworks/CoreWLAN.framework',
                module_globals=globals())

  for iname in CWInterface.interfaceNames():
    interface = CWInterface.interfaceWithName_(iname)
    wifi_parameters= 'Interface:      %s, SSID:           %s, Transmit Rate:  %s, Transmit Power: %s, RSSI:           %s' % (iname, interface.ssid(), interface.transmitRate(), interface.transmitPower(), interface.rssi())
 elif plat=='LINUX':
  interface=Wireless('wlan0')
  
  # Link Quality, Signal Level and Noise Level line
  wifi_parameters= 'Interface:      %s, SSID:           %s, Transmit Rate:  %s, Transmit Power: %s'   % ('wlan0',   interface.getEssid(), interface.getBitrate(), interface.getTXPower())
 
 #record wifi parameters
 print wifi_parameters
 open(channels_file, "a").write(wifi_parameters+'\n')
コード例 #41
0
def get_updater():
    if sys.platform == 'darwin' and getattr(sys, 'frozen', False):
        """
        Use sparkle framework on macOS.

        Examples: https://programtalk.com/python-examples/objc.loadBundle/
        """
        from objc import loadBundle
        bundle_path = os.path.join(os.path.dirname(sys.executable), os.pardir,
                                   'Frameworks', 'Sparkle.framework')
        loadBundle('Sparkle', globals(), bundle_path)
        sparkle = SUUpdater.sharedUpdater()  # noqa: F821
        sparkle.setAutomaticallyChecksForUpdates_(True)
        sparkle.setAutomaticallyDownloadsUpdates_(False)
        sparkle.checkForUpdatesInBackground()
        return sparkle

    else:  # TODO: implement for Linux
        return None
コード例 #42
0
ファイル: WifiDialog.py プロジェクト: hercule115/OSVM
def main():
    # Init Globals instance
    globs.system = platform.system()  # Linux or Windows or MacOS (Darwin)

    try:
        import objc  # WifiDialog
    except ImportError:
        msg = 'Objc module not installed. Disabling Network Selector'
        print(msg)
        globs.networkSelector = False
        globs.disabledModules.append(('Objc', msg))
    else:
        globs.networkSelector = True

    # Init network (Mac only!!!)
    if globs.system == 'Darwin' and globs.networkSelector:
        objc.loadBundle(
            'CoreWLAN',
            bundle_path='/System/Library/Frameworks/CoreWLAN.framework',
            module_globals=globals())

        for iname in CWInterface.interfaceNames():
            interface = CWInterface.interfaceWithName_(iname)

        print("""Interface:      %s
SSID:           %s
BSSID:          %s
Transmit Rate:  %s
Transmit Power: %s
RSSI:           %s""" % (iname, interface.ssid(), interface.bssid(),
                         interface.transmitRate(), interface.transmitPower(),
                         interface.rssi()))

        globs.iface = CWInterface.interface()
        if not globs.iface:
            print('No Network Interface')

    # Create DemoFrame frame, passing globals instance as parameter
    app = wx.App(False)
    frame = MyFrame(None, -1, title="Test")
    frame.Show()
    app.MainLoop()
コード例 #43
0
def setMousePosition(x, y):
    if sys.platform == "linux2":
        import subprocess
        subprocess.call(['xdotool', 'mousemove', str(x), str(y)])
    elif sys.platform == "darwin": 
        import objc
        bndl = objc.loadBundle('CoreGraphics', globals(),
            '/System/Library/Frameworks/ApplicationServices.framework')
        objc.loadBundleFunctions(bndl, globals(),
            [('CGWarpMouseCursorPosition', 'v{CGPoint=dd}')])
        CGWarpMouseCursorPosition((x, y)) 
コード例 #44
0
def fact():
    '''Returns the wifi ssid of the Mac'''
    wifi_ssid = None

    objc.loadBundle(
        'CoreWLAN',
        bundle_path='/System/Library/Frameworks/CoreWLAN.framework',
        module_globals=globals())

    wifi = CWInterface.interfaceNames()
    if wifi:
        for iname in wifi:
            interface = CWInterface.interfaceWithName_(iname)
        if interface:
            try:
                wifi_ssid = interface.ssid()
            except AttributeError:
                pass

    return {factoid: wifi_ssid}
コード例 #45
0
ファイル: plugin.py プロジェクト: 0x73/Flashlight
def run(cmd, lock=False):
    if lock is True:
        # Taken from http://apple.stackexchange.com/a/123738
        import objc
        # We don't load module_globals as we only need the principalClass
        bundle = objc.loadBundle('AppleKeychainExtra',
                                 bundle_path="/Applications/Utilities/Keychain Access.app/Contents/Resources/Keychain.menu",
                                 module_globals=None, scan_classes=False)
        instance = bundle.principalClass().alloc().init()
        instance.performSelector_withObject_("_lockScreenMenuHit:", None)
    else:
        os.system(cmd)
コード例 #46
0
ファイル: _lazyimport.py プロジェクト: mattsolo1/cootControl
def _loadBundle(frameworkName, frameworkIdentifier, frameworkPath):
    if frameworkIdentifier is None:
        bundle = loadBundle(
            frameworkName,
            {},
            bundle_path=frameworkPath,
            scan_classes=False)

    else:
        try:
            bundle = loadBundle(
                frameworkName,
                {},
                bundle_identifier=frameworkIdentifier,
                scan_classes=False)

        except ImportError:
            bundle = loadBundle(
                frameworkName,
                {},
                bundle_path=frameworkPath,
                scan_classes=False)

    return bundle
コード例 #47
0
ファイル: bluetooth.py プロジェクト: TkTech/kizkiz
    def __init__(self):
        objc.loadBundle(
            'IOBluetooth',
            self,
            bundle_path=u'/System/Library/Frameworks/IOBluetooth.framework'
        )

        # Thank you mailing list archives. Figured out how to
        # do these signatures from a 2005 mailing list post.
        objc.setSignatureForSelector(
            'IOBluetoothSDPServiceRecord',
            'getRFCOMMChannelID:',
            'i12@0:o^C'
        )
        objc.setSignatureForSelector(
            'IOBluetoothDevice',
            'openRFCOMMChannelSync:withChannelID:delegate:',
            'i16@0:o^@C@'
        )
        objc.setSignatureForSelector(
            'IOBluetoothRFCOMMChannel',
            'writeSync:length:',
            'i16@0:*S'
        )
コード例 #48
0
ファイル: toggle.py プロジェクト: JinnLynn/alfred-workflows
def toggleBluetooth():
    bundle = objc.loadBundle('IOBluetooth', globals(), bundle_path=objc.pathForFramework('/System/Library/Frameworks/IOBluetooth.framework'))
    if not bundle:
        alfred.exit('Toggle Bluetooth fail. initFrameworkWrapper error')
    fs = [('IOBluetoothPreferenceGetControllerPowerState', 'oI'),('IOBluetoothPreferenceSetControllerPowerState','vI')]
    ds = {}
    objc.loadBundleFunctions(bundle, ds, fs)
    for (name, handle) in fs:
        if not name in ds:
            alfred.exit('Toggle Bluetooth fail. failed to load: {}'.format(name))
    if ds['IOBluetoothPreferenceGetControllerPowerState']() == 1:
        ds['IOBluetoothPreferenceSetControllerPowerState'](0)
        alfred.exit('Bluetooth Disabled.')
    else:
        ds['IOBluetoothPreferenceSetControllerPowerState'](1)
        alfred.exit('Bluetooth Enable.')
コード例 #49
0
ファイル: f5vpn-login.py プロジェクト: mgrubb/f5vpn-login
    def load_SystemConfigurationFramework(self):
        try:
            # If it's already been wrapped, we're done.
            import SystemConfiguration
            return SystemConfiguration
        except ImportError:
            # Nope, so, try again, the hard way...
            import objc
            SystemConfiguration=types.ModuleType('SystemConfiguration')
            SCbndl = objc.loadBundle(SystemConfiguration.__name__, SystemConfiguration.__dict__,
                                     bundle_identifier="com.apple.SystemConfiguration")

            objc.loadBundleFunctions(SCbndl, SystemConfiguration.__dict__, [
                    (u'SCDynamicStoreCreate', '@@@@@'),
                    (u'SCDynamicStoreSetValue', 'B@@@')
                    ])
            return SystemConfiguration
コード例 #50
0
ファイル: macos_counter.py プロジェクト: mynicolas/KeyCounter
 def _check_for_access(self):
     '''Check for accessibility permission'''
     # Because unsigned bundle will fail to call
     # AXIsProcessTrustedWithOptions with a segment falt, we're
     # not currently stepping into this function.
     return
     self.log('Begin checking for accessibility')
     core_services = objc.loadBundle(
         'CoreServices',
         globals(),
         bundle_identifier='com.apple.ApplicationServices'
     )
     objc.loadBundleFunctions(
         core_services,
         globals(),
         [('AXIsProcessTrustedWithOptions', b'Z@')]
     )
     objc.loadBundleFunctions(
         core_services,
         globals(),
         [('kAXTrustedCheckOptionPrompt', b'@')]
     )
     self.log('Bundle com.apple.ApplicationServices loaded')
     try:
         if not AXIsProcessTrustedWithOptions(  # noqa
             {kAXTrustedCheckOptionPrompt: False}  # noqa
         ):
             self.log('Requesting access, Opening syspref window')
             NSWorkspace.sharedWorkspace().openURL_(
                 NSURL.alloc().initWithString_(
                     'x-apple.systempreferences:'
                     'com.apple.preference.security'
                     '?Privacy_Accessibility'
                 )
             )
     except:
         # Unsigned bundle will fail to call AXIsProcessTrustedWithOptions
         self.log((
             'Error detecting accessibility permission status, '
             'KeyCounter might not work'
         ))
     self.log('Access already granted')
コード例 #51
0
ファイル: airport.py プロジェクト: AaronBurchfield/imagr
"""Module for controlling a Wi-Fi interface using CoreWLAN.

https://developer.apple.com/library/mac/documentation/Networking/Reference/CoreWLANFrameworkRef/_index.html
"""

import logging
import os
import time
from . import cocoadialog
from . import defaults

# pylint: disable=g-import-not-at-top
try:
  import objc
  objc.loadBundle('CoreWLAN', globals(),
                  bundle_path='/System/Library/Frameworks/CoreWLAN.framework')

  def R(selector, error_arg_num):
    """Register metadata for CWInterface selectors that return NSError values.

    This tells the Objective-C bridge that the requested selector would normally
    take a reference to an NSError as an argument and should instead return any
    errors alongside the normal return values. This causes the method to return
    a tuple of [Return value, Error or None].

    Args:
      selector: The selector as it's known in Objective-C
      error_arg_num: Which numbered argument would the NSError be passed in
    """
    objc.registerMetaDataForSelector(
        'CWInterface', selector,
コード例 #52
0
ファイル: layout.py プロジェクト: jcooley/miro
from objc import (YES, NO, nil, signature, loadBundle,
                  _C_NSInteger, _C_NSUInteger, _C_NSBOOL)

from miro.plat.frontends.widgets import tableview
from miro.plat.frontends.widgets import wrappermap
from miro.plat.frontends.widgets.base import Container, Bin, FlippedView
from miro.util import Matrix, bitness

try:
    from AppKit import NSScrollerKnobStyleLight
except ImportError:
    # NSScrollerKnobStyleLight is only defined in recent x code versions.
    NSScrollerKnobStyleLight = 2

rbSplitViewBundlePath = '%s/RBSplitView.framework' % NSBundle.mainBundle().privateFrameworksPath()
loadBundle('RBSplitView', globals(), bundle_path=rbSplitViewBundlePath)

_nspointsignature = dict()
_nssizesignature = dict()
_nsrectsignature = dict()
_cgfloatsignature = dict()

_nspointsignature[32] = '{_NSPoint=ff}'
_nspointsignature[64] = '{CGPoint=dd}'

_nssizesignature[32] = '{_NSSize=ff}'
_nssizesignature[64] = '{CGSize=dd}'

_nsrectsignature[32] = ''.join(['{_NSRect=', _nspointsignature[32],
                               _nssizesignature[32], '}'])
_nsrectsignature[64] = ''.join(['{CGRect=', _nspointsignature[64],
コード例 #53
0
ファイル: gmacpyutil.py プロジェクト: SmithersJr/macops
def GetAirportInfo(include_nearby_networks=False):
  """Returns information about current AirPort connection.

  Args:
    include_nearby_networks: bool, if True a nearby_networks key will be in
      the returned dict with a list of detected SSIDs nearby.

  Returns:
    dict: key value pairs from CWInterface data. If an error occurs or there is
      no Wi-Fi interface: the dict will be empty.
  """
  airport_info = {}
  try:
    objc.loadBundle('CoreWLAN', globals(),
                    bundle_path='/System/Library/Frameworks/CoreWLAN.framework')
  except ImportError:
    logging.error('Could not load CoreWLAN framework.')
    return airport_info

  cw_interface_state = {0: u'Inactive',
                        1: u'Scanning',
                        2: u'Authenticating',
                        3: u'Associating',
                        4: u'Running'}

  cw_security = {-1: u'Unknown',
                 0: u'None',
                 1: u'WEP',
                 2: u'WPA Personal',
                 3: u'WPA Personal Mixed',
                 4: u'WPA2 Personal',
                 6: u'Dynamic WEP',
                 7: u'WPA Enterprise',
                 8: u'WPA Enterprise Mixed',
                 9: u'WPA2 Enterprise'}

  cw_phy_mode = {0: u'None',
                 1: u'802.11a',
                 2: u'802.11b',
                 3: u'802.11g',
                 4: u'802.11n'}

  cw_channel_band = {0: u'Unknown',
                     1: u'2 GHz',
                     2: u'5 GHz'}

  iface = CWInterface.interface()  # pylint: disable=undefined-variable
  if not iface:
    return airport_info

  airport_info['name'] = iface.interfaceName()
  airport_info['hw_address'] = iface.hardwareAddress()
  airport_info['service_active'] = bool(iface.serviceActive())
  airport_info['country_code'] = iface.countryCode()
  airport_info['power'] = bool(iface.powerOn())
  airport_info['SSID'] = iface.ssid()
  airport_info['BSSID'] = iface.bssid()
  airport_info['noise_measurement'] = iface.noiseMeasurement()
  airport_info['phy_mode'] = iface.activePHYMode()
  airport_info['phy_mode_name'] = cw_phy_mode[iface.activePHYMode()]
  airport_info['rssi'] = iface.rssiValue()
  airport_info['state'] = iface.interfaceState()
  airport_info['state_name'] = cw_interface_state[iface.interfaceState()]
  airport_info['transmit_power'] = iface.transmitPower()
  airport_info['transmit_rate'] = iface.transmitRate()

  # Get channel information
  cw_channel = iface.wlanChannel()
  if cw_channel:
    airport_info['channel_number'] = cw_channel.channelNumber()
    airport_info['channel_band'] = cw_channel_band[cw_channel.channelBand()]

  # Get security information
  # If the security setting is unknown iface.security() returns NSIntegerMax
  # which is a very large number and annoying to test for in calling scripts.
  # Change any value larger than 100 (the enum currently ends at 10) to -1.
  security = iface.security()
  if security > 100:
    security = -1
  airport_info['security'] = security
  airport_info['security_name'] = cw_security[security]

  # Get nearby network information, if requested
  if include_nearby_networks:
    nearby_networks = []
    try:
      for nw in iface.scanForNetworksWithName_error_(None, None):
        ssid = nw.ssid()
        if ssid not in nearby_networks:
          nearby_networks.append(ssid)
    except TypeError:
      pass
    airport_info['nearby_networks'] = nearby_networks

  return airport_info
コード例 #54
0
ファイル: Keyboard.py プロジェクト: MichaelLeith/pyInputSim
import Quartz
import objc
import os

dirname, filename = os.path.split(os.path.abspath(__file__))
path = dirname + '/objc/Key.framework'

bundle = objc.loadBundle("Key", globals(), bundle_path=objc.pathForFramework(path))

class Keyboard:

    @staticmethod
    def press(code):
        keyEvent = Quartz.CGEventCreateKeyboardEvent(None, Key.getKeyCode_(code), True)
        Quartz.CGEventPost(Quartz.kCGHIDEventTap, keyEvent)
        
    @staticmethod
    def release(code):
        keyEvent = Quartz.CGEventCreateKeyboardEvent(None, Key.getKeyCode_(code), False)
        Quartz.CGEventPost(Quartz.kCGHIDEventTap, keyEvent)


    @staticmethod
    def key(character):
        return Key.getKeyCode_(character)
コード例 #55
0
# Load the framework relative to the executable in the .app bundle

# pyobjc doc recommended moving the framework wrapper to a separate python file.

import sys
import objc

# if app is standalone, import the framework from the app itself. else use the development path.
if hasattr(sys, "frozen"):
    # TODO: what is this objc.pathForFramework?
    #objc.loadBundle("WiiRemoteFramerowk", globals(), bundle_path=objc.pathForFramework(u'@executable_path@/../../Frameworks/WiiRemote.framework'))
    objc.loadBundle("WiiRemoteFramerowk", globals(), bundle_path=u'@executable_path@/../../Frameworks/WiiRemote.framework')
else:
#    objc.loadBundle("WiiRemoteFramework", globals(), bundle_path=u"Frameworks/WiiRemote.framework")
    objc.loadBundle("WiiRemoteFramework", globals(), bundle_path=u"/Users/fdkz/Library/Developer/Xcode/DerivedData/WiiRemoteFramework-azcjpedhwzbkwigedekxtdjiaqcs/Build/Products/Debug/WiiRemote.framework")

# pyobjc 2.3 doc: It is currently necessary to import the wrapper modules for all frameworks that are used by
# your framework. Not doing this may lead to subtle bugs in other parts of the code. This is a limitation of
# PyObjC that will be lifted in a future version.
objc.loadBundle('IOBluetooth', globals(), bundle_path=u'/System/Library/Frameworks/IOBluetooth.framework')

#
# enums from WiiRemote.h
#

class WiiButtonType:
    WiiRemoteAButton = 0
    WiiRemoteBButton = 1
    WiiRemoteOneButton = 2
    WiiRemoteTwoButton = 3
    WiiRemoteMinusButton = 4
コード例 #56
0
_FRAMEWORK_PATH = u'/Library/Frameworks/LightAquaBlue.framework'
if not os.path.isdir(_FRAMEWORK_PATH):
    raise ImportError("Cannot load LightAquaBlue framework, not found at" + \
        _FRAMEWORK_PATH)

try:
    # mac os 10.5 loads frameworks using bridgesupport metadata
    __bundle__ = objc.initFrameworkWrapper("LightAquaBlue",
            frameworkIdentifier="com.blammit.LightAquaBlue",
            frameworkPath=objc.pathForFramework(_FRAMEWORK_PATH),
            globals=globals())

except AttributeError:
    # earlier versions use loadBundle() and setSignatureForSelector()

    objc.loadBundle("LightAquaBlue", globals(), 
       bundle_path=objc.pathForFramework(_FRAMEWORK_PATH))

    # return int, take (object, object, object, output unsigned char, output int)           
    # i.e. in python: return (int, char, int), take (object, object, object)
    objc.setSignatureForSelector("BBServiceAdvertiser", 
        "addRFCOMMServiceDictionary:withName:UUID:channelID:serviceRecordHandle:",
        "i@0:@@@o^Co^I")
        
    # set to take (6-char array, unsigned char, object)
    # this seems to work even though the selector doesn't take a char aray,
    # it takes a struct 'BluetoothDeviceAddress' which contains a char array.
    objc.setSignatureForSelector("BBBluetoothOBEXClient", 
            "initWithRemoteDeviceAddress:channelID:delegate:", 
            '@@:r^[6C]C@')

del objc
コード例 #57
0
#!/usr/bin/python
"""
I didn't create this but I'm storing it so I can reuse it.
http://stackoverflow.com/a/34967364/4811765
"""
import objc

SSID = "MyWifiNetwork"
PASSWORD = "******"

objc.loadBundle('CoreWLAN',
                bundle_path='/System/Library/Frameworks/CoreWLAN.framework',
                module_globals=globals())
iface = CWInterface.interface()
networks, err = iface.scanForNetworksWithName_err_(SSID, None)
network = networks.anyObject()
success, err = iface.associateToNetwork_password_err_(network, PASSWORD, None)
コード例 #58
0
import objc

objc.loadBundle('NetworkStatistics', globals(), bundle_path='/System/Library/PrivateFrameworks/NetworkStatistics.framework/')