2FA on the command line

  • 1 min read
  • Tags: 
  • bash

There is no shortage of OTP 2FA apps availiable for your phone, such as Google Authenticator or Duo Mobile. These apps take an initial secret code, and create a TOTP anytime you need a 2FA code for login. It's also possible to do 2FA on the CLI. Some advantages:

  1. Easy to add, maintain, and backup with a simple key=val text file
  2. Copy/Paste is easier than typing digits displayed on your phone
  3. No issues with being locked out due to dead/lost/new phones

This is accomplised with a utility named oathtool. It can be installed on Debian/Ubuntu via: apt install oathtool. I use a helper script as well as a file of initial secrets.

/usr/local/bin/otp:

#!/usr/bin/env bash
if [ -z $1 ]; then
  echo
  echo "Usage:"
  echo "   otp google"
  echo
  echo "Configuration: $HOME/.otpkeys"
  echo "Format: name=key"
  exit
fi
OTPKEY="$(sed -n "s/${1}=//p" $HOME/.otpkeys)"
if [ -z "$OTPKEY" ]; then
  echo "$(basename $0): Bad Service Name '$1'"
  $0
  exit
fi
oathtool --totp -b "$OTPKEY"

~/.otpkeys:

aws={secret code}
google={secret code}

Getting a 2FA code:

$ otp aws
310645