def writePlist(self, the_token): """Function to write to the plist. Only sets the token for now. Could add in more parameters later.""" if debug: print 'Writing plist' mydict = {} mydict['Token']=the_token NSDictionary.dictionaryWithDictionary_(mydict).writeToFile_atomically_(the_plist, True)
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 createLionEAPkeychainEntry(networkDict): 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): # Clear old value if user['name'][0] == getConsoleUser(): arguments = [security, "delete-generic-password", '-D', '802.1X Password', '-l', networkDict['ssid'], '-a', networkDict['user'], keychain] deleteKeychainPassword(arguments) # Add New Value arguments = [security, "add-generic-password", '-a', networkDict['user'], '-l', networkDict['ssid'], '-D', '802.1X Password', '-s', 'com.apple.network.eap.user.item.wlan.ssid.%s' % networkDict['ssid'], '-w', networkDict['pass'], '-T', 'group://Aiport', '-T', '/System/Library/CoreServices/SystemUIServer.app', '-T', '/Applications/System Preferences.app', '-T', eapolclient, keychain] addKeychainPassword(arguments) try: os.chown(keychain,uid,gid) except: print 'Path not found %s' % keychain except: print 'Key Missing, Skipping'
def do_aperture_library(pathname): # i, s, vol_id, file_id): lib_info_plist = NSDictionary.dictionaryWithContentsOfFile_(pathname+"/Info.plist") print lib_info_plist['CFBundleShortVersionString'] , if lib_info_plist['CFBundleShortVersionString'] == "2.1": print "convert version 2.1 library" return print pathname DataModelVersionDict = NSDictionary.dictionaryWithContentsOfFile_(pathname+"/Aperture.aplib/DataModelVersion.plist") # d1.update(Conversion.pythonCollectionFromPropertyList(ns_dict)) print DataModelVersionDict['databaseUuid'] print DataModelVersionDict
def createLeopEAPkeychainEntry(networkDict): 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): if user['name'][0] == getConsoleUser(): arguments = [security, "add-generic-password", '-a', networkDict['ssid'], '-l', '%s-%s' % (networkDict['ssid'],networkDict['user']), '-D', 'Internet Connect', '-s', networkDict['keyc'], '-w', networkDict['pass'], '-T', 'group://Aiport', '-T', '/System/Library/CoreServices/SystemUIServer.app', '-T', '/Applications/System Preferences.app', '-T', '/usr/libexec/airportd', '-T', eapolclient, keychain] addKeychainPassword(arguments) try: os.chown(keychain,uid,gid) except: print 'Path not found %s' % keychain else: print 'User will not be modified: %s' % user['name'][0] except: print 'Key Missing, Skipping'
def getLocalToken(self): """Get the local token from the PList""" if debug: print 'Getting local token' if os.path.exists(the_plist): if debug: print 'Token exists' mydict = NSDictionary.dictionaryWithContentsOfFile_(the_plist) the_token = mydict['Token'] return the_token else: if debug: print 'No Token Found' return 0
def addUsersEAPProfile(networkDict): 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']: # Process the eap profile profile = home + '/Library/Preferences/com.apple.eap.profiles.plist' createEAPProfile(profile,uid,gid,networkDict) # Process the eap binding profileByHost = home + '/Library/Preferences/ByHost/com.apple.eap.bindings.%s.plist' % getPlatformUUID() createEAPBinding(profileByHost,uid,gid,networkDict) except KeyError: print 'User plist %s does not have a home key' % plistPath
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 deleteUsersKeychainPassword(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']: keychain = home + '/Library/Keychains/login.keychain' print 'Processing keychain: %s' % keychain if os.path.exists(keychain): if user['name'][0] == getConsoleUser(): # Snow Type 1 arguments = [security, "delete-generic-password", '-D', 'AirPort network password', '-a', networkName, '-l', networkName, keychain] deleteKeychainPassword(arguments) # Snow Type 2 arguments = [security, "delete-generic-password", '-D', 'AirPort network password', '-a', 'Airport', '-l', networkName, keychain] deleteKeychainPassword(arguments) # Snow 802.1X type 1 # Updated to remove account type as local user name may mismatch arguments = [security, "delete-generic-password", '-D', '802.1X Password', '-l', 'WPA: %s' % networkName, keychain] deleteKeychainPassword(arguments) # Lion arguments = [security, "delete-generic-password", '-D', '802.1X Password', '-l', networkName, keychain] deleteKeychainPassword(arguments) try: os.chown(keychain,uid,gid) except: print 'Path not found %s' % keychain else: print 'Keychain file: %s does not exist' % keychain except KeyError: print 'User plist %s does not have a home key' % plistPath
'--host2', mailTwo, '--user2', plist['UserName'], '--password2', plist['Password'], '--authmech1', 'CRAM-MD5', '--authmech2', 'LOGIN', '--ssl2', '-subscribe', '-syncinternaldates', '--useuid', '--delete2', ' --expunge2', '--delete2folders', """--regexflag 's/(\A[^\\]\w+\s)|(\s[^\\]\w+)//g""", '--regextrans2', """'s/Sent Messages/Sent Items/g'"""] return command path = '/Shared Items/MigrationLogs/.usersync/' for (path, dirs, files) in os.walk(path): pattern = r'^.*\.plist$' for file in files: if re.search(pattern,file): plistPath = path + file plist = NSDictionary.dictionaryWithContentsOfFile_(plistPath) print genCommand(plist)
def do_aperture_libraryX(d): # python version has dates like: datetime.datetime(2012, 10, 7, 8, 27, 23) d1 = Conversion.pythonCollectionFromPropertyList(d) # d1['kMDItemPath'] = "/Volumes/Taos/model/Heidi Klum.aplibrary/" # fixed library for testing, query can return different order! # d1['kMDItemPath'] = u"/Volumes/Brandywine/Aperture Library—Rialto—lib 23G.aplibrary/" s = d1['kMDItemPath'] print s print_dict(d) print_dict(d1) # # invoke lsdb on the original library file, to get the vol_id, file_id for use when recording # the rest of the info from the library file # # except mysql.connector.Error as err: # if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: # print("Username or password %r and %r?" % (config['user'], config['password'])) # elif err.errno == errorcode.ER_BAD_DB_ERROR: # print "Database %r does not exist." % config['database'] # else: # print 'err:', err # finally: # # ns_dict = NSDictionary.dictionaryWithContentsOfFile_(s+"/Info.plist") d1.update(Conversion.pythonCollectionFromPropertyList(ns_dict)) if d1['CFBundleShortVersionString'] == "2.1": print "convert version 2.1 library" sys.exit() ns_dict = NSDictionary.dictionaryWithContentsOfFile_(s+"/Aperture.aplib/DataModelVersion.plist") d1.update(Conversion.pythonCollectionFromPropertyList(ns_dict)) print d1['databaseUuid'] print_dict(d1) # { # DatabaseMinorVersion = 119; # DatabaseVersion = 110; # createDate = "2012-02-23 19:27:27 +0000"; # databaseUuid = GJVtWD2pRnGz3Qin9Gze4g; # isIPhotoLibrary = 0; # masterCount = 35; # projectCompatibleBackToVersion = 6; # projectVersion = 6; # versionCount = 35; # } # set theDBPosixPath to theApLibPosixPath & "/Database/Library.apdb" dbPath = s + "/Database/Library.apdb" print dbPath import sqlite3 print sqlite3.version # The version number of this module, as a string. This is not the version of the SQLite library. print sqlite3.version_info # The version number of this module, as a tuple of integers. This is not the version of the SQLite library. print sqlite3.sqlite_version # The version number of the run-time SQLite library, as a string. print sqlite3.sqlite_version_info # The version number of the run-time SQLite library, as a tuple of integers. conn = sqlite3.connect(dbPath) print conn cursor = conn.cursor() # overall conunts cursor.execute("SELECT count(*) FROM RKMaster") # print cursor.fetchall() # or use fetchone() print [r for r in cursor]
def do_aperture_library(i, s, vol_id, file_id): db_fields_dict = {'vol_id':vol_id, 'file_id':file_id} print print "[%-2d]==>%s" % (i+1, s) , lib_path = s+"/Info.plist" # print lib_path lib_info_plist = NSDictionary.dictionaryWithContentsOfFile_(s+"/Info.plist") print lib_info_plist['CFBundleShortVersionString'] , if lib_info_plist['CFBundleShortVersionString'] == "2.1": print "convert version 2.1 library" return db_fields_dict['lib_version'] = str(lib_info_plist['CFBundleShortVersionString']) lib_data_model_plist = NSDictionary.dictionaryWithContentsOfFile_(s+"/Aperture.aplib/DataModelVersion.plist") print "(%s)" % (lib_info_plist['CFBundleShortVersionString'] , ) , db_fields_dict['versionCount'] = int(lib_data_model_plist.get('versionCount',0)) db_fields_dict['masterCount'] = int(lib_data_model_plist.get('masterCount',0)) db_fields_dict['databaseUuid'] = str(lib_data_model_plist['databaseUuid']) dbPath = s + "/Database/Library.apdb" # """I am used to (spoiled by?) python's SQLite interface to deal with SQL databases. # One nice feature in python's SQLite's API the "context manager," i.e., python's with statement. # I usually execute queries in the following way: # # import as sqlite # # with sqlite.connect(db_filename) as conn: # query = "INSERT OR IGNORE INTO shapes VALUES (?,?);" # results = conn.execute(query, ("ID1","triangle")) # # With the code above, if my query modifies the database and I forget to run # conn.commit(),the context manager runs it for me automatically upon exiting # the with statement. It also handles exceptions nicely: if an exception # occurs before I commit anything, then the database is rolled back. # # I am now using the MySQLdb interface, which doesn't seem to support # a similar context manager out of the box. How do I create my own? # There is a related question here, but it doesn't offer a complete solution. # # """ conn = sqlite3.connect(dbPath) # print conn cursor = conn.cursor() # Overall counts cursor.execute("SELECT count(*) FROM RKMaster") print " (%d masters)" % ( [r for r in cursor][0][0] , ) # print "==>%s (%s) (%d masters)" % (s, lib_info_plist['CFBundleShortVersionString'] , [r for r in cursor][0][0] ) # print "overall count of masters:", [r for r in cursor][0][0] # Folders and Projects sql = "select ModelID, folderType, name, folderPath from RKFolder" # folderPath is heirarchy information. not currently being used. folder_names = [ r['name'] for r in xda2(cursor, sql) if r['name'] not in folder_names_to_exclude] # print "\nfolders are: (%d) %s" % (len(folder_names), u", ".join(folder_names)) # Volumes sql = "SELECT RKVolume.name FROM RKVolume" volumes_list = xda2(cursor, sql) # print volumes_list if volumes_list == []: print print "no external masters" # print "\nNo (external) volumes; all image versions are within library." db_fields_dict['external_masters_count'] = 0 return db_fields_dict # else: zfd = ", ".join([r['name'] for r in volumes_list]) # print "\nVolumes are:", ", ".join([r['name'] for r in volumes_list]) sql = """SELECT count(*) FROM RKMaster INNER JOIN RKVolume ON RKMaster.fileVolumeUuid = RKVolume.uuid""" cursor.execute( sql ) external_masters_count = [r for r in cursor][0][0] print print "external masters (%d) on %s" % ( external_masters_count, zfd ) db_fields_dict['external_masters_count'] = external_masters_count return db_fields_dict
global debugEnabled debugEnabled = True imapsync = '/usr/local/bin/imapsync.pl' mailOne = 'postfix.mailhost.com' mailTwo = 'exchange.mailhost.com' def genCommand(plist={}): command = [ imapsync, '--host1', mailOne, plist['OldUserName'], '--password1', plist['Password'], '--host2', mailTwo, '--user2', plist['UserName'], '--password2', plist['Password'], '--authmech1', 'CRAM-MD5', '--authmech2', 'LOGIN', '--ssl2', '-subscribe', '-syncinternaldates', '--useuid', '--delete2', ' --expunge2', '--delete2folders', """--regexflag 's/(\A[^\\]\w+\s)|(\s[^\\]\w+)//g""", '--regextrans2', """'s/Sent Messages/Sent Items/g'""" ] return command path = '/Shared Items/MigrationLogs/.usersync/' for (path, dirs, files) in os.walk(path): pattern = r'^.*\.plist$' for file in files: if re.search(pattern, file): plistPath = path + file plist = NSDictionary.dictionaryWithContentsOfFile_(plistPath) print genCommand(plist)