Generating TOTP codes with Python3 (Python3)
One form or another of Two Factor Authentication - 2FA - (sometimes called Two step verification - 2SV) is becoming increasingly common. In particular, Time-based One Time Password (TOTP) is very widely used.
TOTP is implemented in products like Google Authenticator, Microsoft Authenticator and Authy (amongst others). You absolutely should use an app like this for your day-to-day needs. However, sometimes it's useful to have a CLI only option to serve as a backup.
In order to use this Python3 snippet, you'll need to have extracted your TOTP secret from whichever systems you're using it on - it's generally displayed wherever you'd normally go to view the QR code when setting up 2FA.
Ensure, though, that your secrets are stored securely - if they're easily compromised you may lose the benefit of the 2nd factor
Details
- Language: Python3
Snippet
import pyotp
totp = pyotp.TOTP(SECRET)
print("Code:", totp.now())
Usage Example
#!/usr/bin/env python3
#
# pip3 install pyotp
# apt-get install python3-pyotp
#
# Read a secret from stdin and output a TOTP code
# The secret should be provided as a base32 encoded string
#
#
'''
Example:
$ echo apctqfwnowubxzoidazgaj2ba6fs6juc | python3 /tmp/test_totp.py; \
sleep 30; \
echo apctqfwnowubxzoidazgaj2ba6fs6juc | python3 /tmp/test_totp.py
Code: 271142
Code: 280603
'''
import pyotp
import sys
for line in sys.stdin:
totp = pyotp.TOTP(line.rstrip("\n"))
print("Code:", totp.now())