summaryrefslogtreecommitdiff
path: root/contrib/keepassx2pass.py
blob: d8357be952a068334f8812347ea70ac935b3520c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#! /usr/bin/env python

# (C) Copyright 2012 Juhamatti Niemelä <iiska@iki.fi>. All Rights
# Reserved. This file is licensed under the GPLv2+. Please see COPYING
# for more information.

import sys

from subprocess import Popen, PIPE
from xml.etree import ElementTree

def path_for(element, path=''):
    """ Generate path name from elements title and current path """
    title = element.find('title').text
    return '/'.join([path, title])

def import_entry(element, path=''):
    """ Import new password entry to password-store using pass insert
    command """
    proc = Popen(['pass', 'insert', '--force', path_for(element, path)],
              stdin=PIPE, stdout=PIPE)
    proc.communicate(element.find('password').text + "\n")
    proc.wait()

def import_group(element, path=''):
    """ Import all entries and sub-groups from given group """
    npath = path_for(element, path)
    for group in element.findall('group'):
        import_group(group, npath)
    for entry in element.findall('entry'):
        import_entry(entry, npath)


def main(xml_file):
    """ Parse given KeepassX XML file and import password groups from it """
    with open(xml_file) as xml:
        for group in ElementTree.XML(xml.read()).findall('group'):
            import_group(group)

if __name__ == '__main__':
    main(sys.argv[1])