Skip to content

Instantly share code, notes, and snippets.

@Dan-Q
Last active March 8, 2019 16:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Dan-Q/9f03057cddbda08ee7dfe4910f686150 to your computer and use it in GitHub Desktop.
Save Dan-Q/9f03057cddbda08ee7dfe4910f686150 to your computer and use it in GitHub Desktop.
Command-line Google Authenticator (TOTP)
#!/usr/bin/env ruby
# frozen_string_literal: true
# encoding: utf-8
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'rotp'
gem 'thor'
end
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
File.open(File.expand_path('~/.google-authenticator-accounts'), 'a'){|f| f.printf "%-23s %s\n", acName, acCode}
end
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
File.read(File.expand_path('~/.google-authenticator-accounts')).split("\n").reject{|l| l.strip == ''}.each do |account|
if account =~ /^(.+) ([\w\d]+)$/
totp = ROTP::TOTP.new($2)
printf "%-30s %06s %06s\n", $1, totp.at(Time::now.utc), totp.at(Time::now.utc + 30)
end
end
end
default_task :generate
end
GoogleAuthenticator.start
@Dan-Q
Copy link
Author

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: https://danq.me/2018/12/10/second-factor-safety-net/

@sbliven
Copy link

sbliven commented Mar 8, 2019

Thanks!

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

@sbliven
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