#! /usr/bin/env python # -*- coding: utf-8 -*- import subprocess import sys import os from socket import gethostname from netifaces import interfaces, ifaddresses, AF_INET sys.path.append('/usr/scripts/lc_ldap') sys.path.append('/usr/scripts/gestion') sys.path.append('/etc/crans/secrets/') import lc_ldap import config conn=lc_ldap.lc_ldap_admin() ssh_algo = config.sshfp_algo.keys() def ip4_addresses(): ip_list = [] for interface in interfaces(): if interface!='lo' and AF_INET in ifaddresses(interface).keys(): for link in ifaddresses(interface)[AF_INET]: ip_list.append(link['addr']) return ip_list def ssh_keyscan(host,algo): p=subprocess.Popen(["/usr/bin/ssh-keyscan", "-t", "%s" % algo,"%s" % host],stdout=subprocess.PIPE,stderr=subprocess.PIPE) ret=p.communicate()[0].split() key=ret[2] return key def get_machines(): machines=[] for ip in set(ip4_addresses()): machines.extend(conn.search('ipHostNumber=%s' %ip,mode='rw')) return machines def get_local_keys(): keys={} for algo in ssh_algo: if os.path.isfile('/etc/ssh/ssh_host_%s_key.pub' % algo): keys[algo]=open('/etc/ssh/ssh_host_%s_key.pub' % algo).read() return keys def check_keys(keys): return dict([ (algo,key.split()[1] == ssh_keyscan('localhost',algo)) for algo,key in keys.items() ]) def publish_keys(): keys=get_local_keys() validation=check_keys(keys) machines=get_machines() for machine in machines: sshkeys_old=[key.value for key in machine.get('sshFingerprint',[])] sshkeys_new=[key.decode('UTF-8') for algo,key in keys.items() if validation[algo]] if not set(sshkeys_old)==set(sshkeys_new): machine['sshFingerprint']=sshkeys_new machine.save() if __name__ == '__main__' : publish_keys()