Skip to content

Instantly share code, notes, and snippets.

@kwharrigan
Created March 28, 2012 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwharrigan/2226715 to your computer and use it in GitHub Desktop.
Save kwharrigan/2226715 to your computer and use it in GitHub Desktop.
Extract home folder authorized keys into multiple files...
#!/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()
@kwharrigan
Copy link
Author

more flexible than this, which was the first iteration....

@kwharrigan
Copy link
Author

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