Created
March 28, 2012 14:40
-
-
Save kwharrigan/2226715 to your computer and use it in GitHub Desktop.
Extract home folder authorized keys into multiple files...
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
#!/usr/bin/python | |
import sys | |
import os | |
# Run this script on a linux "home" folder | |
def find_authkeys(): | |
''' | |
Walk home folders looking for .ssh/authorized_keys files. | |
If you find them, run authkeys_to_pub | |
''' | |
folderlist = os.walk('.').next()[1] | |
for folder in folderlist: | |
os.chdir(folder) | |
print 'Processed', folder | |
if os.path.exists('.ssh/authorized_keys'): | |
print '**authorized_keys found' | |
authkeys_to_pub('.ssh/authorized_keys', folder) | |
os.chdir('..') | |
def authkeys_to_pub(authkeys_file, username): | |
''' | |
Process a user's authorized_keys file into separate files. | |
Put each pub key in folders key1, key2, ..., keyn all named <user>.pub. | |
''' | |
fh = open(authkeys_file, 'r') | |
known_keys = [] | |
line = fh.readline() | |
ct = 0 | |
while line != '': | |
if line[0] == '#': | |
line = fh.readline() | |
continue | |
if line in known_keys: | |
print 'Skipping duplicate' | |
line = fh.readline() | |
continue | |
ct += 1 | |
keydir = '/tmp/key%d' % ct | |
if not os.path.exists(keydir): | |
os.mkdir(keydir) | |
wf = open('/tmp/key%d/%s.pub' % (ct, username), 'w') | |
wf.write(line) | |
known_keys.append(line) | |
line = fh.readline() | |
if ct != 0: | |
print '%d key(s) processed' % ct | |
if not os.geteuid() == 0: | |
sys.exit('\nThis script only works for root user!\n') | |
find_authkeys() |
I added some lines to prevent duplicates... known keys are appended to the known_keys list as strings and we check against it to remove duplicates.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
more flexible than this, which was the first iteration....