def _add(psafe, pypwsafe, action, changes): """ Add the given record @return: The newly created Record """ assert action == "add" record = Record() for fieldName, fieldValue in changes.items(): if fieldName == "Password": record.setPassword(fieldValue) else: try: record[fieldName] = fieldValue except KeyError, e: log.warn("Failed to update %r with %r=%r", record, fieldName, fieldValue)
def addUpdateDevice(device, loc, psafeLoc, logins = {}, info = {}, passwords = []): """ Add/update info for 'device'. @param loc: The filesystem path to the psafe repo. @type loc: string/file path @param passwords: A list of zero or more passwords to use when decrypting safes. @type passwords: List of strings @param device: The hostname of the device to add/update @type device: string/hostname @param info: A dict of properities to save with the entry. @type info: dict @param logins: A dict of username:password login entries. @type logins: dict @param psafeLoc: Full path to the psafe file to edit. @type psafeLoc: string/filepath @return: None """ safe = None for passwd in passwords: try: safe = PWSafe3(filename = psafeLoc, mode = 'RW', password = passwd) log.debug("%r worked for %r" % (passwd, psafeLoc)) break except: log.debug("%r failed for %r" % (passwd, psafeLoc)) if not safe: log.debug("Unable to open the safe %r" % psafeLoc) safe.lock() try: log.debug("Locked safe %r" % psafeLoc) # Existing entries eeLogins = {} eeInfo = {} # Determine the group name s = device.split('/') deviceFull = s[-1].split('.') deviceHost = deviceFull[0] groupList = s[:-1]+[deviceHost,] groupMatch = '.'.join(groupList) for record in safe.getEntries(): if '.'.join(record.getGroup()) == groupMatch: log.debug("Found a record that is in the device's group: %r" % record) if record.getTitle() == 'Logins': log.debug("Found login %r" % record.getUsername()) eeLogins[record.getUsername()] = record elif record.getTitle() == 'Info': log.debug("Found info %r" % record.getUsername()) eeInfo[record.getUsername()] = record else: log.debug("Related but unknown: %r" % record.getTitle()) else: log.debug("Ignoring %r" % record) for username, password in logins.items(): if eeLogins.has_key(username): eeLogins[username].setPassword(password) log.debug("Set %r to %r" % (eeLogins[username], password)) else: r = Record() r.setGroup(groupList) r.setTitle('Logins') r.setUsername(username) r.setPassword(password) r.setUUID(uuid4()) safe.records.append(r) log.debug("Added record %r" % r) for key_, val in info.items(): if eeInfo.has_key(key_): eeInfo[key_].setPassword(val) log.debug("Set %r to %r" % (eeInfo[key_], val)) else: r = Record() r.setGroup(groupList) r.setTitle('Info') r.setUsername(key_) if '\n' in val: r.setPassword("See Note") r.setNote(val) else: r.setPassword(val) r.setUUID(uuid4()) safe.records.append(r) log.debug("Added record %r" % r) log.debug("Saving safe") safe.save() log.debug("Saved safe") finally: log.debug("Unlocking safe %r" % psafeLoc) safe.unlock() log.debug("Unlocked %r" % psafeLoc)