def deleteUsersEAPProfile(networkName): users = '/var/db/dslocal/nodes/Default/users' listing = os.listdir(users) for plist in listing: # Hardware test for Air excluded = re.compile("^((?!^_|root|daemon|nobody|com.apple.*).)*$") if excluded.match(plist): plistPath = '%s/%s' % (users,plist) print 'Processing: %s' % plistPath user = NSDictionary.dictionaryWithContentsOfFile_(plistPath) try: uid = int(user['uid'][0]) gid = int(user['gid'][0]) for home in user['home']: profile = home + '/Library/Preferences/com.apple.eap.profiles.plist' print 'Processing profile: %s' % profile # Profile if os.path.exists(profile): profileFile = NSMutableDictionary.dictionaryWithContentsOfFile_(profile) profileByHost = home + '/Library/Preferences/ByHost/com.apple.eap.bindings.%s.plist' % getPlatformUUID() if os.path.exists(profileByHost): print 'Updating File: %s' % profileByHost profileByHostFile = NSMutableDictionary.dictionaryWithContentsOfFile_(profileByHost) # Make a copy for enumeration copy = NSDictionary.dictionaryWithDictionary_(profileByHostFile) # Multiple MAC Addresses may exist for mac in copy: index = 0 for key in copy[mac]: if key['Wireless Network'] == networkName: UniqueIdentifier = key['UniqueIdentifier'] print 'Found Network with Identifier: %s' % UniqueIdentifier # Delete the entry and update the file del profileByHostFile[mac][index] writePlist(profileByHostFile,profileByHost) try: os.chown(profileByHost,uid,gid) except: print 'Path not found: %s' % profileByHost profileFileCopy = NSDictionary.dictionaryWithDictionary_(profileFile) profileIndex = 0 print '-' * 80 for key in profileFileCopy['Profiles']: if key['UniqueIdentifier'] == UniqueIdentifier: print 'Found network: %s' % key['UserDefinedName'] # Delete the entry and update the file del profileFile['Profiles'][index] writePlist(profileFile,profile) os.chown(profile,uid,gid) profileIndex += 1 index += 1 else: print 'File not found: %s' % profileByHost else: print 'Profile file: %s does not exist' % profile except KeyError: print 'User plist %s does not have a home key' % plistPath
def leopardRemoveWireless(networkName): plistPath = '/Library/Preferences/SystemConfiguration/preferences.plist' # Sanity checks for the plist if os.path.exists(plistPath): try: pl = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath) except: print 'Unable to parse file at path: %s' % plistPath sys.exit(1) else: print 'File does not exist at path: %s' % plistPath sys.exit(1) print 'Processing preference file: %s' % plistPath # Create a copy of the dictionary due to emuration copy = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath) # Iterate through network sets for Set in copy['Sets']: UserDefinedName = copy['Sets'][Set]['UserDefinedName'] print 'Processing location: %s' % UserDefinedName for enX in copy['Sets'][Set]['Network']['Interface']: print 'Processing interface: %s' % enX # I think this will always be a single key but this works either way for key in copy['Sets'][Set]['Network']['Interface'][enX]: print 'Processing Service: %s' % key # Try to grab the PreferredNetworks key if any try: # Iterate through preferred network sets index = 0 for PreferredNetwork in copy['Sets'][Set]['Network']['Interface'][enX][key]['PreferredNetworks']: SSID_STR = PreferredNetwork['SSID_STR'] print 'Processing SSID: %s' % SSID_STR # If the preferred network matches our removal SSID if SSID_STR == networkName: print 'Found SSID %s to remove' % SSID_STR # Delete our in ram copy print 'Processing Set: %s' % Set print 'Processing enX: %s' % enX print 'Processing key: %s' % key try: print 'Attempting delete of Set: %s for Interface:%s Named:%s Index:%d' % (Set,enX,key,index) del pl['Sets'][Set]['Network']['Interface'][enX][key]['PreferredNetworks'][index] print 'Deleted set: %s' % Set except IndexError: print 'Unable to remove Received Out of bounds error for index %d' % index index += 1 except KeyError: print 'Skipping interface without PreferredNetworks' # Make a copy of plist shutil.copy(plistPath,plistPath + '.old') # Write the plist to a file writePlist(pl,plistPath) removeKnownNetwork(networkName) deleteUsersKeychainPassword(networkName) deleteUsersEAPProfile(networkName)
def createKnownNetwork(networkDict): print 'Creating KnownNetworks entry' # There were some MacBook Airs that shipped with 10.5 path = '/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist' # Set to root as the owner for good measure uid = 0 gid = 80 if os.path.exists(path): plist = NSMutableDictionary.dictionaryWithContentsOfFile_(path) else: plist = NSMutableDictionary.alloc().init() plist['KnownNetworks'] = {} guid = networkDict['guid'] plist['KnownNetworks'][guid] = {} plist['KnownNetworks'][guid]['SSID_STR'] = networkDict['ssid'] plist['KnownNetworks'][guid]['Remembered channels'] = [networkDict['chan'],] plist['KnownNetworks'][guid]['SecurityType'] = networkDict['sect'] # If we are adding a non WPA2 Enterprise network add the keychain item if networkDict['type'] == 'WPA2': plist['KnownNetworks'][guid]['Unique Password ID'] = networkDict['keyc'] plist['KnownNetworks'][guid]['_timeStamp'] = NSDate.date() exportFile = path plist.writeToFile_atomically_(exportFile,True) try: os.chown(path,uid,gid) except: print 'Path not found %s' % path
def createRecentNetwork(networkDict): path = '/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist' # Set to root as the owner for good measure uid = 0 gid = 80 if os.path.exists(path): plist = NSMutableDictionary.dictionaryWithContentsOfFile_(path) else: plist = NSMutableDictionary.alloc().init() port = getPlatformPortName() # Check for non-existant keys if not port in plist.keys(): plist[port] = {} # Make sure the Array is there if not 'RecentNetworks' in plist[port].keys(): plist[port]['RecentNetworks'] = [] _RecentNetworks = {} _RecentNetworks['SSID_STR'] = networkDict['ssid'] _RecentNetworks['SecurityType'] = networkDict['sect'] _RecentNetworks['Unique Network ID'] = networkDict['guid'] _RecentNetworks['Unique Password ID'] = networkDict['keyc'] plist[port]['RecentNetworks'].append(_RecentNetworks) exportFile = path plist.writeToFile_atomically_(exportFile,True) try: os.chown(path,uid,gid) except: print 'Path not found %s' % path
def removeKnownNetwork(networkName): plistPath = '/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist' # Sanity check to make sure preferences are the there. if os.path.exists(plistPath): pl = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath) else: return 1 # Copy the dictionary for mutation during enumeration copy = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath) # 10.7 style try: index = 0 for key in copy['RememberedNetworks']: name = pl['RememberedNetworks'][index]['SSIDString'] if name == networkName: print 'Found %s at index %d' % (name,index) del pl['RememberedNetworks'][index] index += 1 except: print 'Key RememberedNetworks not found' # 10.5 Style # Clean up KnownNetworks key try: for guid in copy['KnownNetworks'].keys(): if copy['KnownNetworks'][guid]['SSID_STR'] == networkName: del pl['KnownNetworks'][guid] except: print 'Key KnownNetworks not found' # Clean up top level key port = getPlatformPortName() # There were some MacBook Airs that shipped with 10.5 try: if port in copy.keys(): index = 0 try: for key in copy[port]['RecentNetworks']: if key['SSID_STR'] == networkName: del pl[port]['RecentNetworks'][index] index += 1 except: print 'No key RecentNetworks' except: print 'Unable to cleanup %s' % port writePlist(pl,plistPath)
def createEAPBinding(path,uid,gid,networkDict): macAddress = getAirportMac() if os.path.exists(path): plist = NSMutableDictionary.dictionaryWithContentsOfFile_(path) else: plist = NSMutableDictionary.alloc().init() plist[macAddress] = [] _item = {} _item['UniqueIdentifier'] = networkDict['keyc'] _item['Wireless Network'] = networkDict['ssid'] plist[macAddress].append(_item) exportFile = path plist.writeToFile_atomically_(exportFile,True) try: os.chown(path,uid,gid) except: print 'Path not found %s' % path
def addPreferredNetwork(networkDict): path = '/Library/Preferences/SystemConfiguration/preferences.plist' plist = NSMutableDictionary.dictionaryWithContentsOfFile_(path) for _Sets in plist['Sets'].keys(): for Interface in plist['Sets'][_Sets]['Network']['Interface'].keys(): if 'AirPort' in plist['Sets'][_Sets]['Network']['Interface'][Interface].keys(): if not 'PreferredNetworks' in plist['Sets'][_Sets]['Network']['Interface'][Interface]['AirPort'].keys(): plist['Sets'][_Sets]['Network']['Interface'][Interface]['AirPort']['PreferredNetworks'] = [] _PreferredNetworks = {} _PreferredNetworks['SSID_STR'] = networkDict['ssid'] _PreferredNetworks['SecurityType'] = networkDict['sect'] _PreferredNetworks['Unique Network ID'] = networkDict['guid'] # Add keychain item reference if not 802.1x or Open if networkDict['type'] == 'WPA2': _PreferredNetworks['Unique Password ID'] = networkDict['keyc'] plist['Sets'][_Sets]['Network']['Interface'][Interface]['AirPort']['PreferredNetworks'].append(_PreferredNetworks) plist.writeToFile_atomically_(path,True)
def createEAPProfile(path,uid,gid,networkDict): if os.path.exists(path): plist = NSMutableDictionary.dictionaryWithContentsOfFile_(path) else: plist = NSMutableDictionary.alloc().init() plist['Profiles'] = [] # item entry _Profiles = {} # EAPClientConfiguration EAPClientConfiguration = {} AcceptEAPTypes = [] _AcceptEAPTypes = networkDict['eapt'] AcceptEAPTypes = [_AcceptEAPTypes] # Top Level EAPClientConfiguration keys EAPClientConfiguration['AcceptEAPTypes'] = AcceptEAPTypes EAPClientConfiguration['Description'] = 'Automatic' EAPClientConfiguration['EAPFASTProvisionPAC'] = True EAPClientConfiguration['EAPFASTUsePAC'] = True EAPClientConfiguration['TLSVerifyServerCertificate'] = False EAPClientConfiguration['TTLSInnerAuthentication'] = networkDict['iath'] EAPClientConfiguration['UserName'] = networkDict['user'] EAPClientConfiguration['UserPasswordKeychainItemID'] = networkDict['keyc'] if not osVersion['minor'] == LEOP: EAPClientConfiguration['Wireless Security'] = networkDict['type'] # Top Level item keys _Profiles['EAPClientConfiguration'] = EAPClientConfiguration _Profiles['UniqueIdentifier'] = networkDict['keyc'] _Profiles['UserDefinedName'] = 'WPA: %s' % networkDict['ssid'] if not osVersion['minor'] == LEOP: _Profiles['Wireless Security'] = networkDict['type'] # Merge the data with current plist plist['Profiles'].append(_Profiles) exportFile = path plist.writeToFile_atomically_(exportFile,True) try: os.chown(path,uid,gid) except: print 'Path not found %s' % path
def leopardAddWireless(networkDict={}): plistPath = '/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist' # Sanity check to make sure preferences are the there. if os.path.exists(plistPath): pl = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath) # Copy the dictionary for mutation during enumeration copy = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath) # 10.5 Style # Grab UUID if already in network list found = False print 'Checking for existing Keychain GUID in KnownNetworks' try: for key in copy['KnownNetworks'].keys(): if copy['KnownNetworks'][key]['SSID_STR'] == networkDict['ssid']: networkDict['guid'] = copy['KnownNetworks'][key]['Unique Password ID'] print 'Found existing reference to wireless password guid: %s' % networkDict['guid'] found = True except: print 'Key KnownNetworks not found' # If this not an OPEN network then add keychain # Updated to not add blank keychain entry for Open networks if 'pass' in networkDict.keys() and not networkDict['type'] == "OPEN": """ Removing Keychain entries for system due to bug in 10.5 """ #print 'Network has password generating keychain arguments...' #keychain = '/Library/Keychains/System.keychain' #arguments = [security, # "add-generic-password", # '-a', # networkDict['ssid'], # '-l', # networkDict['ssid'], # '-D', # 'AirPort network password', # '-s', # networkDict['guid'], # '-w', # networkDict['pass'], # '-T', # 'group://Aiport', # '-T', # '/System/Library/CoreServices/SystemUIServer.app', # '-T', # '/Applications/System Preferences.app', # '-T', # '/usr/libexec/airportd', # keychain] #addKeychainPassword(arguments) users = '/var/db/dslocal/nodes/Default/users' listing = os.listdir(users) for plist in listing: # Hardware test for Air excluded = re.compile("^((?!^_|root|daemon|nobody|com.apple.*).)*$") if excluded.match(plist): plistPath = '%s/%s' % (users,plist) print 'Processing: %s' % plistPath user = NSDictionary.dictionaryWithContentsOfFile_(plistPath) try: uid = int(user['uid'][0]) gid = int(user['gid'][0]) for home in user['home']: keychain = home + '/Library/Keychains/login.keychain' print 'Processing keychain: %s' % keychain if os.path.exists(keychain): # -U causing segmentation fault, removed sudo if user['name'][0] == getConsoleUser(): arguments = [security, "add-generic-password", '-a', networkDict['ssid'], '-l', networkDict['ssid'], '-D', 'AirPort network password', '-s', 'AirPort Network', '-w', networkDict['pass'], '-T', 'group://Aiport', '-T', '/System/Library/CoreServices/SystemUIServer.app', '-T', '/Applications/System Preferences.app', keychain] addKeychainPassword(arguments) arguments = [kcutil, user['home'][0], user['name'][0], networkDict['pass'], configFile] addKeychainPassword(arguments) try: os.chown(keychain,uid,gid) except: print 'Path not found: %s' % keychain else: print 'Keychain file: %s does not exist' % keychain except: print 'User plist %s does not have a home key' % plistPath else: print 'No password is specified, skipping keychain actions' port = 'Airport' if networkDict['type'] == 'WPA2 Enterprise': createKnownNetwork(networkDict) createRecentNetwork(networkDict) addUsersEAPProfile(networkDict) createLeopEAPkeychainEntry(networkDict) addPreferredNetwork(networkDict) else: # We can automatically connect to WPA PSK type networks leopardRemoveWireless(networkDict['ssid']) connectToNewNetwork(port,networkDict)
def main(): global debugEnabled debugEnabled = False # Check for envrionmental variables try: userName = os.environ['USER_NAME'] except KeyError: userName = '' try: userPass = os.environ['PASS_WORD'] except KeyError: userPass = '' # Process Arguments if(debugEnabled): print 'Processing Arguments: ', sys.argv[1:] try: options, remainder = getopt.getopt(sys.argv[1:], 'u:p:f:d', ['username='******'password='******'plist=', 'debug' ]) except getopt.GetoptError: print "Syntax Error!" return 1 for opt, arg in options: if opt in ('-u', '--username'): userName = arg elif opt in ('-p', '--password'): userPass = arg elif opt in ('-f', '--plist'): plistPath = arg elif opt in ('-d', '--debug'): debugEnabled = True # Sanity Checks if len(options) < 1: showUsage() print '--> Not enough options given' return 1 # Check the current directory if os.path.exists('wifiutil.settings.plist'): plistPath = 'wifiutil.settings.plist' try: plistPath except UnboundLocalError: showUsage() print '--> You must specify a plist path.' return 1 if os.path.exists(plistPath): plist = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath) else: print 'File does not exist: %s' % plistPath return 1 global configFile configFile = plistPath # Get OS Version global osVersion osVersion = getSystemVersion() # Disconnect from wireless toggleAirportPower('off') # Check for Networks to remove if 'networkRemoveList' in plist.keys(): networkRemoveList = plist['networkRemoveList'] # Loop through our remove list for network in networkRemoveList: # Process os specific directives removeWireless(osVersion,network) else: print 'No networks specified to remove' # Check for Networks to Add if 'networkAddList' in plist.keys(): networkAddList = plist['networkAddList'] # Loop through our add list for networkDict in networkAddList: # Add our username and password to the config if 'user' not in networkDict.keys(): networkDict['user'] = userName if 'pass' not in networkDict.keys(): networkDict['pass'] = userPass # Remove the password for OPEN network if networkDict['type'] == 'OPEN': del networkDict['pass'] # Generate our wireless & keychain entry guids, not recommended if not 'guid' in networkDict.keys(): networkDict['guid'] = str(uuid.uuid1()).upper() if not 'keyc' in networkDict.keys(): networkDict['keyc'] = str(uuid.uuid1()).upper() # Process os specific directives addWireless(osVersion,networkDict) else: print 'No networks specified to add' # Restore Airport Power toggleAirportPower('on')
#/usr/bin/python """ This script is designed as a pre-build step for iOS Xcode projects. To use it, do the following: 1. Create a new pre-build step 2. Set the Shell field to "/usr/bin/python" 3. Select your target in "Provide build settings from" 4. Copy everything below the hash line into the input box This script should be accompanied by the post-build step in post-build.py """ ############################################### import os import datetime from Cocoa import NSMutableDictionary plistPath = "%(s)s/%(n)s/%(n)s-Info.plist" % {'s': os.getenv('SRCROOT'), 'n': os.getenv('PRODUCT_NAME')} info = NSMutableDictionary.dictionaryWithContentsOfFile_(plistPath) now = datetime.datetime.now() bundleVersion = "%.4d%.2d%.2d.%.2d%.2d" % (now.year, now.month, now.day, now.hour, now.minute) info['CFBundleVersion'] = bundleVersion os.rename(plistPath, "%s.temp" % plistPath) info.writeToFile_atomically_(plistPath, True)