Generating TOTP codes with Python3

Published: 2020-08-10 15:12:09 +0000
Categories: 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


import pyotp

totp = pyotp.TOTP(SECRET)

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 

$ echo apctqfwnowubxzoidazgaj2ba6fs6juc | python3 /tmp/; \
sleep 30; \
echo apctqfwnowubxzoidazgaj2ba6fs6juc | python3 /tmp/

Code: 271142
Code: 280603


import pyotp
import sys

for line in sys.stdin:
    totp = pyotp.TOTP(line.rstrip("\n"))



2fa, totp, python3, 2sv, ssv,

Latest Posts

Copyright © 2021 Ben Tasker | Sitemap | Privacy Policy
Available at and http://phecoopwm6x7azx26ctuqcp6673bbqkrqfeoiz2wwk36sady5tqbdpqd.onion