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 |
This comment has been minimized.
This comment has been minimized.
Thanks! Users should note that the account codes should not contain spaces. The last word of It is also a good idea to protect the secret keys somewhat: |
This comment has been minimized.
This comment has been minimized.
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
This comment has been minimized.
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/