This repository has been archived by the owner on Jan 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1password_export.py
executable file
·208 lines (185 loc) · 5.75 KB
/
1password_export.py
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#!/usr/bin/env python
from pathlib import Path
from subprocess import Popen, STDOUT, PIPE
from logging import getLogger, basicConfig
from os import environ
import json
from operator import itemgetter
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, FileType
from urllib.parse import urlsplit, urlunsplit
from itertools import chain
import pandas as pd
ONE_PASSWORD_CLI = "op"
GROUPING_DELIMITER = " :: "
MONTHS = """
January
February
March
April
May
June
July
August
September
October
November
December
""".strip().split()
_logger = getLogger()
def op(*args, fail_on_exc=True, quiet=False):
p = Popen(
[
ONE_PASSWORD_CLI,
*args,
],
stdout=PIPE,
stderr=PIPE,
# env=environ,
)
o, e = p.communicate()
if o:
o = json.loads(o.strip().decode("utf-8"))
if e:
error = e.strip().decode()
if fail_on_exc:
raise RuntimeError(
f"[{ONE_PASSWORD_CLI} {args}] exited with error {error!r} and code {p.returncode}"
)
if not quiet:
_logger.error(f'"{error}"')
return o
def get_vaults():
return sorted(map(itemgetter("name"), op("list", "vaults")))
def simplify_url(url):
"""Remove params and fragment"""
scheme, location, path, query, fragment = urlsplit(url)
return urlunsplit((scheme, location, path, "", ""))
def as_credit_card(_fields):
fields = dict((f["n"], f["v"]) for f in _fields)
_i = str(fields["expiry"])
expiry_year, expiry_month = _i[:4], _i[4:]
return f"""NoteType:Credit Card
Language:en-US
Name on Card:{fields['cardholder']}
Type:{fields['type'].capitalize()}
Number:{fields['ccnum']}
Security Code:{fields['cvv']}
Start Date:,
Expiration Date:{MONTHS[int(expiry_month) - 1]},{expiry_year}
Notes:"""
def to_csv(args):
if args.max_count:
_logger.info(f"Will fetch max {args.max_count} items")
if args.dumper:
_logger.info(f"Will dump items to {args.dumper.name} as we fetch them")
for vault_name in get_vaults():
grouping = GROUPING_DELIMITER.join([args.grouping, vault_name])
_logger.info(
f"Fetching items from {vault_name} vault, will be grouped to {grouping}"
)
# Lastpass CSV: url,username,password,totp,extra,name,grouping,fav
for i, _item in enumerate(
sorted(
filter(
lambda i: i["trashed"] == "N",
op("list", "items", "--vault", vault_name),
),
key=itemgetter("uuid"),
),
1,
):
if args.max_count and i > args.max_count:
break
uuid = _item["uuid"]
if args.include and uuid not in args.include:
continue
_logger.info(f"{i:3d}. Fetching item with id {uuid}")
item = op("get", "item", uuid)
overview = item["overview"]
details = item["details"]
fields = details.get("fields", [])
def _fields():
for f in fields:
if f["designation"] in ["username", "password"]:
yield f["designation"], f["value"]
secure_note = not overview.get("url")
if not fields:
_logger.warning(
f"Item with {uuid} does not have details/fields, will export as a Secure Note"
)
secure_note = True
try:
def _iter_sfields():
for s in details.get("sections", []):
yield s.get("fields")
ccard_fields = chain.from_iterable(_iter_sfields())
note_content = as_credit_card(ccard_fields)
except:
note_content = details["notesPlain"]
d = dict(
username="",
password="",
# XXX if not url, it is a LastPass Secure Note
url="http://sn" if secure_note else simplify_url(overview["url"]),
totp="", # no idea what this is
extra=note_content,
name=overview["title"],
grouping=grouping,
fav="0",
_id=uuid,
)
d.update(_fields())
if args.dumper:
json.dump(d, args.dumper)
print(file=args.dumper)
args.dumper.flush()
yield d
if __name__ == "__main__":
parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument(
"-d",
"--debug",
action="store_true",
help="Show debug logs",
)
parser.add_argument(
"-u",
"--dumper",
help="Dump raw items to the file",
type=FileType("w"),
metavar="PATH",
)
parser.add_argument(
"-i",
"--include",
help="Only show output for this UUID",
metavar="UUID",
nargs="+",
)
parser.add_argument(
"-g",
"--grouping",
help="Folder to be created in LastPass",
default="1password_import",
metavar="STRING",
)
parser.add_argument(
"-n", "--max-count", help="Max item count to fetch", type=int, metavar="INT"
)
parser.add_argument(
"-o",
"--output-file",
required=True,
help="Output file",
type=Path,
metavar="PATH",
)
args = parser.parse_args()
basicConfig(
level="DEBUG" if args.debug else "INFO",
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
_logger.debug(args)
items = pd.DataFrame(to_csv(args))
_logger.info(f"Writing {len(items.index)} record(s) to {args.output_file}")
items.to_csv(args.output_file, index=False)