Created
September 28, 2021 14:13
-
-
Save hennevogel/b83c7aa598310d14615a928bdb60a80e to your computer and use it in GitHub Desktop.
Get the information logins via SSH key
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# journalctl -u sshd --utc -o json --since "6 hours ago" | ruby who.rb | |
# written by Victor Pereira <vpereira@suse.com> | |
require 'json' | |
require 'open3' | |
require 'optparse' | |
class JournalLog | |
def self.parse | |
return [] if STDIN.tty? | |
# Ruby 2.7 = filter_map | |
STDIN.read.each_line.map do |line| | |
JSON.parse(line) | |
end.select do |json_data| | |
json_data['MESSAGE'] =~ /Accepted publickey/ | |
end.map do |data| | |
{ key: data['MESSAGE'].split('SHA256:').last, timestamp: data['__REALTIME_TIMESTAMP'] } | |
end | |
end | |
end | |
class RunCommand | |
def initialize(auth_keys_file) | |
@auth_keys_file = auth_keys_file | |
end | |
def run(key) | |
out, err, status = Open3.capture3(*ssh_keygen_params) | |
xout, xerr, xstatus = Open3.capture3(*grep_params(key), stdin_data: out) | |
xout | |
end | |
private | |
def grep_params(key) | |
['/usr/bin/grep', "SHA256:#{key}"] | |
end | |
def ssh_keygen_params | |
['/usr/bin/ssh-keygen', '-lf', @auth_keys_file] | |
end | |
end | |
if $PROGRAM_NAME == __FILE__ | |
authorized_keys_file = ARGV[0].nil? ? "#{ENV['HOME']}/.ssh/authorized_keys" : ARGV[0] | |
JournalLog.parse.reject do |entry| | |
RunCommand.new(authorized_keys_file).run(entry[:key]).empty? | |
end.each do |entry| | |
cmd = RunCommand.new(authorized_keys_file).run(entry[:key]) | |
puts "#{Time.at(entry[:timestamp].to_i/1000000)} - #{cmd}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment