Copy the ssh_keys_users facter from Tor
[mirror/dsa-puppet.git] / modules / ssh / lib / facter / ssh_keys_users.rb
1 require 'etc'
2
3 # this fact will iterate over all the known users (as defined by the
4 # Etc module) and look in their .ssh directory for public keys. the
5 # public keys are exported in a user => [keys] hash, where keys are
6 # stored in the array without distinction of type
7 Facter.add(:ssh_keys_users) do
8   setcode do
9     keys_hash = {}
10     Etc.passwd { |user|
11       keys = {}
12       Dir.glob(File.join(user.dir, '.ssh', '*.pub')).each { |filepath|
13         if FileTest.file?(filepath)
14           regex = %r{^ssh-(\S+) (\S+)\s?(.+)?$}
15           begin
16             line = File.open(filepath).read.chomp
17             if (match = regex.match(line))
18                 keys[File.basename(filepath)] = {
19                     'type' => match[1],
20                     'key' => match[2],
21                     'comment' => match[3],
22                     'line' => line,
23                 }
24             end
25           rescue
26             puts "cannot read user SSH key: " + user.name
27           end
28         end
29       }
30       keys_hash[user.name] = keys if not keys.empty?
31     }
32     keys_hash
33   end
34 end