Two-Factor Authentication on the Command Line

snippet

Prerequisite is PyOTP, which we set up within a virtual environment:

$ python3 -m venv venv
$ . venv/bin/activate
$ pip install pyotp
$ deactivate

With that, we can use the following script to generate TOTPs:

#!/usr/bin/env sh

set -e

secret="…"
root=`dirname "$0"`
root=`realpath "$root"`

generate() {
    python3 -c "import pyotp; totp = pyotp.TOTP('$secret'); print(totp.now())"
}

cd "$root"
. venv/bin/activate

if [ "$1" = "-c" ]; then
    generate | pbcopy
else
    generate
fi