| #!/usr/bin/python2 |
| import json |
| import os |
| import subprocess |
| import sys |
| import tarfile |
| import urllib2 |
| import pwd |
| |
| import linaro_ldap |
| |
| |
| def web_sync(url): |
| if not os.path.exists('./tmp'): |
| os.mkdir('./tmp') |
| tf = urllib2.urlopen(url) |
| with tarfile.open(fileobj=tf, mode="r|gz") as tf: |
| tf.extractall(path='./tmp') |
| |
| for p in os.listdir('./tmp'): |
| os.rename('./tmp/' + p, p) |
| |
| |
| def ldap_sync(): |
| fname = 'ssh_keys.json' |
| with open(fname + '.tmp', 'w') as f: |
| json.dump(linaro_ldap.get_users_and_keys(), f) |
| os.rename(f.name, fname) |
| subprocess.check_output(['/usr/sbin/nss_updatedb', 'ldap']) |
| with tarfile.open('ldap-files.tgz.tmp', 'w:gz') as tf: |
| tf.add('group.db') |
| tf.add('passwd.db') |
| tf.add('ssh_keys.json') |
| os.rename('ldap-files.tgz.tmp', 'ldap-files.tgz') |
| |
| |
| def keys(user): |
| u = pwd.getpwnam(user) |
| if u.pw_uid < 10000: # local user |
| with open(os.path.join(u.pw_dir, '.ssh/authorized_keys')) as f: |
| try: |
| print f.read().strip('\n') |
| except: |
| return |
| |
| with open('ssh_keys.json') as f: |
| data = json.load(f) |
| keys = data.get(user) |
| if keys: |
| for key in keys: |
| print(key[1]) |
| |
| |
| if __name__ == '__main__': |
| if len(sys.argv) not in (2, 3): |
| sys.exit('Usage: %s --sync [URL]|<user>' % sys.argv[0]) |
| |
| os.chdir('/var/lib/misc') |
| if sys.argv[1] == '--sync': |
| if len(sys.argv) == 3: |
| web_sync(sys.argv[2]) |
| else: |
| ldap_sync() |
| else: |
| keys(sys.argv[1]) |