Skip to content

Instantly share code, notes, and snippets.

@metux
Created September 21, 2023 10:53
Show Gist options
  • Save metux/ce43da58d9759019a0fbf4d25ccb1b00 to your computer and use it in GitHub Desktop.
Save metux/ce43da58d9759019a0fbf4d25ccb1b00 to your computer and use it in GitHub Desktop.
simple TOTP token generator w/ qrcode image decoding
#!/usr/bin/env python3
# deps: zbar-tools, oathtool
#
# call it as toptp-token.py <qrimage-filename>
#
# 1. decodes the qrcode image via zbar-img
# 2. parses totp url and extracts parameters (secret, stepping, algo, ...)
# 3. calls oathtool to generate the current token
import subprocess
import sys
from urllib.parse import urlparse
from urllib.parse import parse_qs
if len(sys.argv) < 2:
print("missing param")
sys.exit(1)
url = subprocess.check_output(['zbarimg', '-q', '--nodbus', sys.argv[1]]).decode('utf8')
# print("URL: "+url)
parsed_url = urlparse(url)
parsed_qs = parse_qs(parsed_url.query)
if 'secret' not in parsed_qs:
print("no secret")
exit(1)
secret = parsed_qs['secret'][0]
cmd = cmd = ['oathtool', '-b', secret ]
if 'algorithm' in parsed_qs:
cmd.append('--totp='+parsed_qs['algorithm'][0].strip())
else:
cmd.append('--totp')
if 'digits' in parsed_qs:
cmd.append('--digits='+parsed_qs['digits'][0].strip())
if 'period' in parsed_qs:
cmd.append('--time-step-size='+parsed_qs['period'][0].strip())
# print(cmd)
code = subprocess.check_output(cmd).decode('utf8').strip()
print(code)
@metux
Copy link
Author

metux commented Oct 4, 2024

I am now almost required to use 2fa to login into GH. How this script works?

Just call it with a photo of the QR code: it will print out the decoded token.

By the way, if you've got an android device, I'd recomment FreeOTP.

@metux
Copy link
Author

metux commented Oct 4, 2024

We don't need 2FA on GitHub!

Agreed. But unfortunately, they won't listen to us. Typical for these Redmond boys.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment