[PYTHON] Steps to get KeePassX key on OS X with one command line

I wanted to get a KeePassX key in an environment where the GUI cannot be used, so I tried it.

Introduction of kptool

If you search, Summary of tools used in Command Line vol.2 will appear immediately. Prepare the environment for running kptool with Python.

GitHub shirou/kptool

$ git clone https://github.com/shirou/kptool.git
$ python kptool/kptool/kptool.py path/to/kdbfile
Traceback (most recent call last):
  File "kptool/kptool/kptool.py", line 9, in <module>
    from keepassdb import keepassdb
  File "/Users/east/git/kptool/kptool/keepassdb/keepassdb.py", line 6, in <module>
    from Crypto.Cipher import AES
ImportError: No module named Crypto.Cipher

I was immediately told that there was no Crypto. Install with pip.

$ pip install pycrypto 
-bash: pip: command not found

I was told that there is no pip. Install pip.

$ sudo easy_install pip
Searching for pip
Reading http://pypi.python.org/simple/pip/
Best match: pip 1.5.4
Downloading https://pypi.python.org/packages/source/p/pip/pip-1.5.4.tar.gz#md5=834b2904f92d46aaa333267fb1c922bb
Processing pip-1.5.4.tar.gz
Running pip-1.5.4/setup.py -q bdist_egg --dist-dir /tmp/easy_install-8UYX4X/pip-1.5.4/egg-dist-tmp-HXMDdl
warning: no files found matching 'pip/cacert.pem'
warning: no files found matching '*.html' under directory 'docs'
warning: no previously-included files matching '*.rst' found under directory 'docs/_build'
no previously-included directories found matching 'docs/_build/_sources'
Adding pip 1.5.4 to easy-install.pth file
Installing pip script to /usr/local/bin
Installing pip2.7 script to /usr/local/bin
Installing pip2 script to /usr/local/bin
 
Installed /Library/Python/2.7/site-packages/pip-1.5.4-py2.7.egg
Processing dependencies for pip
Finished processing dependencies for pip

Installation of pip is complete.

$ pip install pycrypto
Command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/47/lrzh0xp935z2ppgpth8cx44w0000gn/T/pip_build_east/pycrypto/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/47/lrzh0xp935z2ppgpth8cx44w0000gn/T/pip-4slDJi-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /private/var/folders/47/lrzh0xp935z2ppgpth8cx44w0000gn/T/pip_build_east/pycrypto
Storing debug log for failure in /Users/east/Library/Logs/pip.log

Somehow an error occurred in red letters. Run with sudo.

$ sudo pip install pycrypto
 
Successfully installed pycrypto
Cleaning up...

It seems to have worked.

$ python kptool/kptool/kptool.py path/to/kdbfile
Enter password ['path/to/kdbfile']
Password: 
kptool> list

If the title list of the entry saved in the corresponding kdb appears in list, it is successful.

Modify kptool

I wanted to get it in one shot, so I modified kptool by copying.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import argparse
import getpass
import datetime
import readline
 
from keepassdb import keepassdb
 
if __name__ == '__main__':
 
  parser = argparse.ArgumentParser(description='search entry from keepass DB')
  parser.add_argument('kdb_file',
                      nargs=1,
                      help = 'keepass DB file path')
  parser.add_argument('title',
                      nargs=1,
                      help = 'entry title')
  parser.add_argument('-p', '--password')
 
  args = parser.parse_args()
 
  if (not args.password):
    password = getpass.getpass()
  else:
    password = args.password
 
  try:
    k = keepassdb.KeepassDBv1(args.kdb_file[0], password)
  except ValueError:
    print("Invalid password.")
    exit(1)
 
  for e in k.get_entries():
    title = e['title'].encode('utf-8')
    if (title == args.title[0]):
      print("id:%s" % e['id'].encode('utf-8'))
      print("title:%s" % title)
      print("url:%s" % e['url'].encode('utf-8'))
      print("username:%s" % e['username'].encode('utf-8'))
      print("password:%s" % e['password'].encode('utf-8'))

did it! !!

If a password is given with the -p option, that password will be used. Prompt for password if there is no -p option. I am printing data that seems to be necessary.

Get the key from the command line

#!/bin/sh

KEEPASS_SCRIPT=~/git/kptool/kptool/getentry.py
LOCAL_KDB_FILE=path/to/kdbfile
LOCAL_KDB_ENTRY=The title of the key you want

HOGE_PASSWORD=`python ${KEEPASS_SCRIPT} ${LOCAL_KDB_FILE} ${LOCAL_KDB_ENTRY} | grep password | cut -d ':' -f 2`
echo $KEEPASS_SCRIPT

If you write a shell script like this, you can easily get it just by entering the password. I'm echoing here, but please note that echoing the password is not a very correct operation. It feels good to incorporate it into an appropriate program and use it.

further...

For example, if the kdb file is a secondary linkage of another kdb file, The -p option works.

#!/bin/sh

KEEPASS_SCRIPT=~/git/kptool/kptool/test.py
LOCAL_KDB_FILE=path/to/kdbfile
LOCAL_KDB_ENTRY=The title of the primary key you want
APP_KDB_FILE="$1"
APP_KDB_ENTRY='HogeApp (hoge) hogehoge'

if [ -z $APP_KDB_FILE ]
then
  echo "Usage: $0 path/to/app.kdb"
  exit 1
fi

APP_KDB_PASSWORD=`python ${KEEPASS_SCRIPT} ${LOCAL_KDB_FILE} ${LOCAL_KDB_ENTRY} | grep password | cut -d ':' -f 2`
APP_URL=`python ${KEEPASS_SCRIPT} ${APP_KDB_FILE} "${APP_KDB_ENTRY}" -p ${APP_KDB_PASSWORD} | grep url | head -n 1 |cut -d ':' -f 2`
APP_PASSWORD=`python ${KEEPASS_SCRIPT} ${APP_KDB_FILE} "${APP_KDB_ENTRY}" -p ${APP_KDB_PASSWORD} | grep password | head -n 1 |cut -d ':' -f 2`

Data can be easily acquired just by entering the primary key, improving efficiency! We were able to build an environment that works by just entering the minimum required password.

The feeling is exactly Kachakachakacha ...

The end

Recommended Posts

Steps to get KeePassX key on OS X with one command line
Steps to use the AWS command line interface (Python / awscli) on Mac OS X
How to install caffe on OS X with macports
How to install Theano on Mac OS X with homebrew
Get started with the Python framework Django on Mac OS X
Steps to get Caffe into Mac OS X 10.10 in CPU Mode
How to get the key on Amazon S3 with Boto 3, implementation example, notes
Convert XLSX to CSV on the command line
Preparing to use aws cli on Mac OS X
How to do zero-padding in one line with OpenCV
Very easy to install SciPy on Mac OS X
Yum command to access MySQL with Python 3 on Linux
Steps to measure coverage and get badges on codecov.io
Install PyQt5 with homebrew on Mac OS X Marvericks (10.9.2)
Steps to install the latest version of OpenCV on OS X El Capitan without Homebrew
Memo to get the value on the html-javascript side with jupyter
Use Python 3 introduced with command line tools on macOS Catalina
I want to start a jupyter environment with one command
Test Python with Miniconda on OS X and Linux with travis-ci
Memo on Mac OS X
Create another version of Python conda environment with one command line
How to get a string from a command line argument in python
How to get all traffic through VPN with OpenVPN on Linux
I tried to get started with Bitcoin Systre on the weekend
I tried to display GUI on Mac with X Window System
[Python] How to get a value with a key other than value with Enum
Install lp_solve on Mac OS X and call it with python.
GSI_DEM to geotiff conversion → UTM conversion → ascii conversion only on Ubuntu command line
How to install Theano on Mac OS X 10.10 (using pyenv, anaconda)