Skip to content

Instantly share code, notes, and snippets.

Last active March 8, 2019 16:09
What would you like to do?
Command-line Google Authenticator (TOTP)
#!/usr/bin/env ruby
# frozen_string_literal: true
# encoding: utf-8
require 'bundler/inline'
gemfile do
source ''
gem 'rotp'
gem 'thor'
class GoogleAuthenticator < Thor
desc 'add', 'add a new account'
def add
print 'New account name: '
acName = STDIN.gets.strip
print 'New account code: '
acCode = STDIN.gets.strip'~/.google-authenticator-accounts'), 'a'){|f| f.printf "%-23s %s\n", acName, acCode}
desc 'generate', 'generate TOTP codes'
def generate
printf "%-30s %3s (%02ds) %4s\n", 'Account', 'Now', (30 - (Time::now.utc.to_i % 30)), 'Next'
puts '-' * 47'~/.google-authenticator-accounts')).split("\n").reject{|l| l.strip == ''}.each do |account|
if account =~ /^(.+) ([\w\d]+)$/
totp =$2)
printf "%-30s %06s %06s\n", $1,, + 30)
default_task :generate
Copy link

Dan-Q commented Dec 10, 2018

Run ./google-authenticator.rb add to add new accounts. You'll be asked for a name and a code. Account details are written to ~/.google-authenticator.

Run ./google-authenticator.rb to list 'now' and 'next' TOTP codes for all added accounts.

Further reading:

Copy link

sbliven commented Mar 8, 2019


Users should note that the account codes should not contain spaces. The last word of ~/.google-authenticator-accounts is used as the code, with everything else taken as the account name. Account codes should be either 16 or 32 letters/digits (e.g. 80 or 160 bits).

It is also a good idea to protect the secret keys somewhat: chmod 600 ~/.google-authenticator-accounts

Copy link

sbliven commented Mar 8, 2019

BTW, I made some small fixes in my fork if your interested.

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