JupyterHub支持多用户和ldap认证(2)

       在上一篇博客中已经介绍了怎么安装jupyterhub和增加新用户,但是必须在linux终端手动添加新用户。接下来介绍怎么添加ldap统一认证,并自动创建新用户,且不需要再手动添加密码。

1、安装jupyterhub-ldapauthenticator
pip install jupyterhub-ldapauthenticator

2、配置jupyterhub_config.py
(1)在上一篇文章中已经介绍了怎么生成配置配置文件,建议放在 /etc/jupyterhub/目录下,打开该文件,定位到c.JupyterHub.authenticator_class.
(2)在下一行开始添加以下配置信息(确保jupyterhub服务器和ldap服务器网络是通的):

c.JupyterHub.authenticator_class = 'ldapauthenticator.LDAPAuthenticator'
c.LDAPAuthenticator.server_address = '172.xx.xx.xx'  #ldap服务器地址
c.LDAPAuthenticator.server_port = 389                #ldap端口
c.LDAPAuthenticator.bind_dn_template = [             #template以实际为准
    "uid={username},ou=People,dc=xx,dc=xx",
]

3、修改ldapauthenticator.py文件
(1)修改anaconda_home/lib/python3.6/site-packages/ldapauthenticator目录下的ldapauthenticator.py文件。
(2)在头文件添加 import pwd,os
(3)在authenticate函数前面添加如下程序:

def system_user_exists(self, username):
        """Check if the user exists on the system"""
        try:
            pwd.getpwnam(username)
        except KeyError:
            return False
        else:
            return True

def add_system_user(self, username, password):
        """Create a new local UNIX user on the system.

        Tested to work on FreeBSD and Linux, at least.
        """
        res = os.system('useradd  %(name1)s -s /bin/nologin' % {'name1':username})
        if res:
            self.log.warn('user %s create failure' % username)
            return False
            
        res = os.system('echo %(pass)s |passwd --stdin %(name1)s' % {'name1': username, 'pass':password})
        if res:
            self.log.warn('user %s password create failure' % username)
            return False
        
        return True

(4)在authenticate函数里面的 return username 前面添加如下程序即可:

if not self.system_user_exists(username):
    res = self.add_system_user(username,password)
    if not res:
        return None

这样在ldap认证通过以后如果本地没有这个用户,就会自动创建。但是这种做法在ldap删除用户以后无法自动删除本地用户,这也是jupyterhub官方不支持创建用户的原因。

猜你喜欢

转载自blog.csdn.net/haveanybody/article/details/84934985