Skip to content

Instantly share code, notes, and snippets.

@SeriousBug
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SeriousBug/e9f33873d10ad944cbe6 to your computer and use it in GitHub Desktop.
Save SeriousBug/e9f33873d10ad944cbe6 to your computer and use it in GitHub Desktop.
A python script to import a LastPass CSV export to pass.
"""
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
"""
#!/usr/bin/env python3
import csv
import sys
import argparse
import subprocess
EXPECTED_COLUMNS = ["url", "username", "password", "extra", "name", "grouping", "fav"]
def check_header(header_tuple):
"""Check the header to identify the order of the columns."""
header = {}
for i, column in enumerate(header_tuple):
header[column] = i
if all((x in header for x in EXPECTED_COLUMNS)):
print("CSV format identified.")
return header
else:
print("Unable to identify CSV format.")
sys.exit(1)
def parse_row(row, header):
"""Parse the given row into a dict, based on the header."""
parsed = {}
for column, key in header.items():
parsed[column] = row[key]
return parsed
def insert_pass(path, input):
subprocess.check_output(["pass", "insert", "--multiline", path], input=input)
def enter_password(parsed):
"""Enter the given row into pass as domain/username."""
path = "{}/{}".format(parsed["name"], parsed["username"])
if parsed["extra"] == "":
password_input = bytes(parsed["password"], "utf-8")
else:
password_input = bytes('\n'.join((parsed["password"], "Extra:", parsed["extra"])), "utf-8")
insert_pass(path, password_input)
def enter_secure_note(parsed):
"""Enter the given secure note into pass."""
path = "{}/{}".format(parsed["grouping"], parsed["name"])
note_input = bytes(parsed["extra"], "utf-8")
insert_pass(path, note_input)
def insert_row(row, header):
"""Insert the given row into pass."""
parsed = parse_row(row, header)
if all((parsed[column] != "" for column in ("username", "password", "name"))):
enter_password(parsed)
elif all((parsed[column] != "" for column in ("name", "grouping", "extra"))):
enter_secure_note(parsed)
elif parsed["name"].startswith("Generated Password for "):
# Skip all generated passwords
print("Skipping {}.".format(parsed["name"]))
else:
# Skipping this password, notify the user for manual entry
print("\nUnable to import the following password:")
print("URL: {:<30}".format(parsed["url"]))
print("Name: {}".format(parsed["name"]))
print("Group: {}".format(parsed["grouping"]))
print("Username: {}".format(parsed["username"]))
print("Password: {}\n".format(parsed["password"]))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Import LastPass csv export into pass.")
parser.add_argument("pass_file", type=str,
help="The CSV file exported from LastPass.")
args = parser.parse_args()
with open(args.pass_file) as pass_file:
pass_reader = csv.reader(pass_file, strict=True)
# Check the CSV header
header = check_header(pass_reader.__next__())
for row in pass_reader:
insert_row(row, header)
print("\nDone.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment