Skip to content

Instantly share code, notes, and snippets.

@jsgarmon
Last active January 28, 2022 22:27
Show Gist options
  • Save jsgarmon/85c41fbb9784dbb8df61d1aceaf90d81 to your computer and use it in GitHub Desktop.
Save jsgarmon/85c41fbb9784dbb8df61d1aceaf90d81 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
'''
Produce a one-time password (OTP) from a secret or a json
file and label.
example: get_otp.py -f ./my-secret.json -l github
example: get_otp.py -s NY30
'''
import json
import sys
from argparse import ArgumentParser
from oathtool import generate_otp
def get_args():
parser = ArgumentParser(description="Return a OTP from a QR code or secret key")
parser.add_argument('-f','--file', type=str,
required=False,
help="The file where secrets are stored (json format)")
parser.add_argument('-l','--label', type=str,
required=False,
help="The name of the secret within the file. Required if --file is specified.")
parser.add_argument('-s','--secret', type=str,
required=False,
help="The actual QR code or secret")
return parser.parse_args()
def get_secret(filename, label):
'''If filename, label specified, retrieve the secret from the file'''
with open(filename) as f:
auth = json.load(f)
s = None
for i in auth:
if i['label'] == label:
s = i['secret']
break
if s == None:
print("Label %s not found" % label)
sys.exit(1)
return s
def get_otp(secret):
try:
otp = generate_otp(secret)
except:
print("Failed to get OTP from secret. Ensure secret is in correct format")
raise
return otp
if __name__ == '__main__':
args = get_args()
if args.secret:
otp = get_otp(args.secret)
else:
if not (args.file and args.label):
print("Filename and label must be given if no secret is given")
sys.exit(1)
otp = get_otp(get_secret(args.file, args.label))
print(otp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
OSZAR »