Created
July 28, 2015 08:43
-
-
Save dicbobz/20750b6ca0bb423a0d93 to your computer and use it in GitHub Desktop.
Allow users to update their own ssh key
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 | |
# rick@drawbrid.ge | |
import sys | |
import ldap | |
import getpass | |
import struct | |
from base64 import decodestring as decode | |
import argparse | |
parser = argparse.ArgumentParser(description="Update SSH Keys") | |
parser.add_argument('--file','-f', action='store', type=str, nargs=1, default='~/.ssh/id_rsa.pub', help='Supply ssh public key file') | |
parser.add_argument('--user','-u', action='store', type=str, nargs=1, required=True, help ='Supply your ldap username') | |
args = parser.parse_args() | |
def getsshkey(keyfile): | |
# Checks keystring is actually ssh-rsa type | |
openssh_pubkey = open(keyfile).readline().rstrip('\n') | |
type, key_string, comment = openssh_pubkey.split() | |
data = decode(key_string) | |
int_len = 4 | |
str_len = struct.unpack('>I', data[:int_len])[0] | |
if data[int_len:int_len+str_len] == type: | |
return openssh_pubkey | |
else: | |
print("Improper key type, or encoding error. We only allow RSA type ssh-keys.\nGenerate a proper key like this." | |
"\nssh-keygen -t rsa -b 2048 -C youremailaddress") | |
sys.exit(1) | |
def changeSshKey(user, ldap_pass, openssh_pubkey): | |
user_dn = 'uid=' + user + ',ou=users,dc=domain,dc=net' | |
try: | |
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) | |
l = ldap.initialize("ldaps:/yoursecureserver:636/") | |
l.set_option(ldap.OPT_REFERRALS,0) | |
l.set_option(ldap.OPT_PROTOCOL_VERSION,3) | |
l.set_option(ldap.OPT_X_TLS,ldap.OPT_X_TLS_DEMAND) | |
l.set_option(ldap.OPT_X_TLS_DEMAND,True) | |
l.set_option(ldap.OPT_DEBUG_LEVEL,255) | |
l.simple_bind_s(user_dn, ldap_pass) | |
mod_attrs = [ (ldap.MOD_REPLACE, 'sshPublicKey', openssh_pubkey) ] | |
l.modify_s(user_dn, mod_attrs) | |
print("Public SSH key for %s updated") % user_dn | |
l.unbind_s() | |
except ldap.LDAPError, e: | |
print e | |
if __name__ == "__main__": | |
ldap_pass = getpass.getpass('Enter your LDAP password: ') | |
user = str(args.user[0]).lower() | |
file = args.file[0] | |
key = getsshkey(file) | |
changeSshKey(user, ldap_pass, key) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment