Create google auth OTP from command line

I recently added OTP authentication using pam_google_authenticator.so to most of my machines. It's non-trivial to set up, especially if you have system users with limited capabilities that need to be able to log in non-interactively, but all in all it feels good to have a little more security.

When logging in from the local network OTP auth is skipped, but I frequently log into remote machines and lost too much time getting the token off my phone. I created the script below which outputs the token and adds it to my X clipboard. The secret can either be provided on the command line or read from a file.

Raw
#!/usr/bin/env python

import argparse
import os
import sys
from subprocess import Popen, PIPE

import onetimepass as otp


def pad_secret(secret):
    """
    Pad secret if necessary
    """
    while len(secret) % 8 != 0:
        secret += "="
    return secret


def show_token(secret):
    token = "{:06d}\n".format(otp.get_totp(secret))
    sys.stdout.write(token)
    p = Popen(["xclip", "-i"], stdin=PIPE)
    p.communicate(input=str.encode(token))


def get_secret_from_file(secretfile):
    with open(secretfile, "r") as fh:
        return fh.readline().strip()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Show OTP codes")
    parser.add_argument(
        "secretfile",
        const=os.path.expanduser("~/.google_authenticator"),
        default=os.path.expanduser("~/.google_authenticator"),
        nargs="?",
        help="Read secret from file, consider first line only",
    )
    parser.add_argument("--secret", "-s", type=str, help="Pass secret")
    args = parser.parse_args()

    if args.secret:
        show_token(pad_secret(args.secret))
    else:
        show_token(pad_secret(get_secret_from_file(args.secretfile)))

0 comments

Reply

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.
DjangoPythonBitcoinTuxDebianHTML5 badgeSaltStackUpset confused bugMoneyHackerUpset confused bugX.OrggitFirefoxWindowMakerBashIs it worth the time?i3 window managerWagtailContainerIrssiNginxSilenceUse a maskWorldInternet securityPianoFontGnuPGThunderbirdJenkinshome-assistant-logo