Kerberos、LDAP、SSSD 部署示例教程

Kerberos、LDAP、SSSD 部署示例教程

此篇文章主要用于示例如何在 Centos7.x 操作系统上手动部署 KERBEROS LDAP SSSD 服务,便于用户了解这 3 个服务的部署以及使用过程。如果需要实现自动部署,可前往 DataLight 官网下载 DataLight 平台,通过开源项目自动化部署上述服务。

操作过程中,将假设未来会在完全离线的私有化环境中进行安装部署,因此,除了下载资源需要在有外网的节点上进行,其余操作,均可在完全离线的环境中进行,但其中需要确保系统的版本与依赖项是相关的。

在进行如下部署操作之前,请先更新国内 yum 源:

mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup

curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo

yum clean all 
yum makecache

yum -y install yum-utils
yum -y install epel-release
yum makecache

一、Kerberos

1.1 下载 Kerberos 资源包

mkdir -p /data/install/KERBEROS/kerberos-package

# 全量下载(推荐)
repotrack -p /data/install/KERBEROS/kerberos-package krb5-server krb5-libs krb5-workstation
# 增量下载(可能不适用于离线环境)
yumdownloader --resolve --destdir=/data/install/KERBEROS/kerberos-package krb5-server krb5-libs krb5-workstation

1.2 安装 Kerberos

cd /data/install/KERBEROS/kerberos-package

yum -y localinstall ./*.rpm --disablerepo='*'

1.3 配置 Kerberos

1.3.1 配置 KRB5
vi /etc/krb5.conf
[libdefaults]
    default_realm = DATALIGHT
    dns_lookup_realm = false
    dns_lookup_kdc = false
    ticket_lifetime = 24h
    renew_lifetime = 7d
    forwardable = true

[realms]
    DATALIGHT = {
        kdc = node01
        admin_server = node01
    }

[domain_realm]
    .datalight = DATALIGHT
    datalight = DATALIGHT

[logging]
 default = FILE:/data/datalight/logs/KERBEROS/krb5libs.log
 kdc = FILE:/data/datalight/logs/KERBEROS/krb5kdc.log
 admin_server = FILE:/data/datalight/logs/KERBEROS/kadmind.log
1.3.2 配置 KDC
vi /var/kerberos/krb5kdc/kdc.conf
[kdcdefaults]
 kdc_ports = 88
 kdc_tcp_ports = 88

[realms]
 DATALIGHT = {
  acl_file = /var/kerberos/krb5kdc/kadm5.acl
  dict_file = /usr/share/dict/words
  admin_keytab = /var/kerberos/krb5kdc/kadm5.keytab
  supported_enctypes = aes256-cts:normal aes128-cts:normal des3-hmac-sha1:normal arcfour-hmac:normal camellia256-cts:normal camellia128-cts:normal des-hmac-sha1:normal des-cbc-md5:normal des-cbc-crc:normal
 }
1.3.3 配置管理员 ACL
vi /var/kerberos/krb5kdc/kadm5.acl
*/admin@DATALIGHT *

1.4 初始化 Kerberos 数据库

kdb5_util create -s -r DATALIGHT -P 123456
# 输入密码:123456

1.5 启用 Kerberos 服务

systemctl start krb5kdc
systemctl start kadmin
systemctl enable krb5kdc
systemctl enable kadmin

1.6 创建管理员

kadmin.local -q "addprinc -pw 123456 admin@DATALIGHT"

1.7 验证 Kerberos

kinit admin@DATALIGHT
klist

二、LDAP

2.1 下载 LDAP 资源包

mkdir -p /data/install/LDAP/ldap-package

# 全量下载(推荐)
repotrack -p /data/install/LDAP/ldap-package openldap openldap-servers openldap-clients
# 增量下载(可能不适用于离线环境)
yumdownloader --resolve --destdir=/data/install/LDAP/ldap-package openldap openldap-servers openldap-clients

2.2 安装 LDAP

cd /data/install/LDAP/ldap-package

yum -y localinstall ./*.rpm --disablerepo='*'

2.3 配置 LDAP

2.3.1 复制数据库文件并授权
cp /usr/share/openldap-servers/DB_CONFIG.example /var/lib/ldap/DB_CONFIG

chown -R ldap. /var/lib/ldap/DB_CONFIG
2.3.2 启动服务
systemctl start slapd
systemctl enable slapd
systemctl status slapd
2.3.3 生成管理员密码
slappasswd -s 123456
# 结果: {SSHA}mG6XXowEsfbeE21cZHKHLaf3yUDKktxg
2.3.4 创建修改数据库密码文件
vi ~/modify-olcRootPw.ldif
dn: olcDatabase={0}config,cn=config
changetype: modify
add: olcRootPW
olcRootPW: {SSHA}mG6XXowEsfbeE21cZHKHLaf3yUDKktxg
ldapadd -Y EXTERNAL -H ldapi:/// -f ~/modify-olcRootPw.ldif
2.3.5 加载必要 Schema
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/core.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/cosine.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/nis.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/inetorgperson.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/collective.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/corba.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/duaconf.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/dyngroup.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/java.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/misc.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/openldap.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/ppolicy.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/pmi.ldif
2.3.6 修改域名
vi ~/modify-domain.ldif
dn: olcDatabase={1}monitor,cn=config
changetype: modify
replace: olcAccess
olcAccess: {0}to * by dn.base="gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth" read by dn.base="cn=admin,dc=datalight,dc=com" read by * none
 
dn: olcDatabase={2}hdb,cn=config
changetype: modify
replace: olcSuffix
olcSuffix: dc=datalight,dc=com
 
dn: olcDatabase={2}hdb,cn=config
changetype: modify
replace: olcRootDN
olcRootDN: cn=admin,dc=datalight,dc=com
 
dn: olcDatabase={2}hdb,cn=config
changetype: modify
replace: olcRootPW
olcRootPW: {SSHA}mG6XXowEsfbeE21cZHKHLaf3yUDKktxg
 
dn: olcDatabase={2}hdb,cn=config
changetype: modify
add: olcAccess
olcAccess: {0}to attrs=userPassword,shadowLastChange by dn="cn=admin,dc=datalight,dc=com" write by anonymous auth by self write by * none
olcAccess: {1}to dn.base="" by * read
olcAccess: {2}to * by dn="cn=admin,dc=datalight,dc=com" write by * read
ldapmodify -Y EXTERNAL -H ldapi:/// -f ~/modify-domain.ldif
2.3.7 开启 MemberOf
vi ~/add-memberof.ldif

dn: cn=module{0},cn=config
cn: modulle{0}
objectClass: olcModuleList
objectclass: top
olcModuleload: memberof.la
olcModulePath: /usr/lib64/openldap
 
dn: olcOverlay={0}memberof,olcDatabase={2}hdb,cn=config
objectClass: olcConfig
objectClass: olcMemberOf
objectClass: olcOverlayConfig
objectClass: top
olcOverlay: memberof
olcMemberOfDangling: ignore
olcMemberOfRefInt: TRUE
olcMemberOfGroupOC: groupOfUniqueNames
olcMemberOfMemberAD: uniqueMember
olcMemberOfMemberOfAD: memberOf
vi ~/modify-refint-1.ldif
dn: cn=module{0},cn=config
add: olcmoduleload
olcmoduleload: refint
vi ~/add-refint-2.ldif
dn: olcOverlay=refint,olcDatabase={2}hdb,cn=config
objectClass: olcConfig
objectClass: olcOverlayConfig
objectClass: olcRefintConfig
objectClass: top
olcOverlay: refint
olcRefintAttribute: memberof uniqueMember manager owner
# 依次执行
ldapadd -Q -Y EXTERNAL -H ldapi:/// -f ~/add-memberof.ldif
ldapmodify -Q -Y EXTERNAL -H ldapi:/// -f ~/modify-refint-1.ldif
ldapadd -Q -Y EXTERNAL -H ldapi:/// -f ~/add-refint-2.ldif
2.3.8 创建基础 DN
vi ~/base.ldif
dn: dc=datalight,dc=com
objectClass: top
objectClass: dcObject
objectClass: organization
o: datalight
dc: datalight
 
dn: cn=admin,dc=datalight,dc=com
objectClass: organizationalRole
cn: admin
 
dn: ou=User,dc=datalight,dc=com
objectClass: organizationalUnit
ou: User

dn: ou=Group,dc=datalight,dc=com
objectClass: organizationalUnit
ou: Group
ldapadd -x -D cn=admin,dc=datalight,dc=com -w 123456 -f ~/base.ldif
2.3.9 验证配置
ldapsearch -x -H ldap://node01 -b "dc=datalight,dc=com"
# 或
ldapsearch -x -b "dc=datalight,dc=com"

2.4 部署 PhpLDAPAdmin

2.4.1 下载 PhpLDAPAdmin
mkdir -p /data/install/LDAPVIEWER/phpldap-package

# 全量下载(推荐)
repotrack -p /data/install/LDAPVIEWER/phpldap-package phpldapadmin
# 增量下载(可能不适用于离线环境)
yumdownloader --resolve --destdir=/data/install/LDAPVIEWER/phpldap-package phpldapadmin
2.4.2 安装 PhpLDAPAdmin
cd /data/install/LDAPVIEWER/phpldap-package

yum -y localinstall ./*.rpm --disablerepo='*'
2.4.3 修改配置
2.4.3.1 httpd.conf
vi /etc/httpd/conf/httpd.conf
#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see 
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.  
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so 'log/access_log'
# with ServerRoot set to '/www' will be interpreted by the
# server as '/www/log/access_log', where as '/log/access_log' will be
# interpreted as '/log/access_log'.

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path.  If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the
# Mutex directive, if file-based mutexes are used.  If you wish to share the
# same ServerRoot for multiple httpd daemons, you will need to change at
# least PidFile.
#
ServerRoot "/etc/httpd"

#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to 
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 8007

#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
Include conf.modules.d/*.conf

#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.  
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User apache
Group apache

# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition.  These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#

#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed.  This address appears on some server-generated pages, such
# as error documents.  e.g. admin@your-domain.com
#
ServerAdmin root@localhost

#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80

#
# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other 
# <Directory> blocks below.
#
# <Directory />
#     Options Indexes FollowSymLinks
#     AllowOverride None
# </Directory>
<Directory />

    Options Indexes FollowSymLinks

    AllowOverride None

</Directory>
#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#

#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/var/www/html"

#
# Relax access to content within /var/www.
#
<Directory "/var/www">
    AllowOverride None
    # Allow open access:
    Require all granted
</Directory>

# Further relax access to the default document root:
<Directory "/var/www/html">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
    AllowOverride None

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
</Directory>

#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ".ht*">
    Require all denied
</Files>

#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"

#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn

<IfModule log_config_module>
    #
    # The following directives define some format nicknames for use with
    # a CustomLog directive (see below).
    #
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    #
    # The location and format of the access logfile (Common Logfile Format).
    # If you do not define any access logfiles within a <VirtualHost>
    # container, they will be logged here.  Contrariwise, if you *do*
    # define per-<VirtualHost> access logfiles, transactions will be
    # logged therein and *not* in this file.
    #
    #CustomLog "logs/access_log" common

    #
    # If you prefer a logfile with access, agent, and referer information
    # (Combined Logfile Format) you can use the following directive.
    #
    CustomLog "logs/access_log" combined
</IfModule>

<IfModule alias_module>
    #
    # Redirect: Allows you to tell clients about documents that used to 
    # exist in your server's namespace, but do not anymore. The client 
    # will make a new request for the document at its new location.
    # Example:
    # Redirect permanent /foo http://www.example.com/bar

    #
    # Alias: Maps web paths into filesystem paths and is used to
    # access content that does not live under the DocumentRoot.
    # Example:
    # Alias /webpath /full/filesystem/path
    #
    # If you include a trailing / on /webpath then the server will
    # require it to be present in the URL.  You will also likely
    # need to provide a <Directory> section to allow access to
    # the filesystem path.

    #
    # ScriptAlias: This controls which directories contain server scripts. 
    # ScriptAliases are essentially the same as Aliases, except that
    # documents in the target directory are treated as applications and
    # run by the server when requested rather than as documents sent to the
    # client.  The same rules about trailing "/" apply to ScriptAlias
    # directives as to Alias.
    #
    ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

</IfModule>

#
# "/var/www/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule mime_module>
    #
    # TypesConfig points to the file containing the list of mappings from
    # filename extension to MIME-type.
    #
    TypesConfig /etc/mime.types

    #
    # AddType allows you to add to or override the MIME configuration
    # file specified in TypesConfig for specific file types.
    #
    #AddType application/x-gzip .tgz
    #
    # AddEncoding allows you to have certain browsers uncompress
    # information on the fly. Note: Not all browsers support this.
    #
    #AddEncoding x-compress .Z
    #AddEncoding x-gzip .gz .tgz
    #
    # If the AddEncoding directives above are commented-out, then you
    # probably should define those extensions to indicate media types:
    #
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz

    #
    # AddHandler allows you to map certain file extensions to "handlers":
    # actions unrelated to filetype. These can be either built into the server
    # or added with the Action directive (see below)
    #
    # To use CGI scripts outside of ScriptAliased directories:
    # (You will also need to add "ExecCGI" to the "Options" directive.)
    #
    #AddHandler cgi-script .cgi

    # For type maps (negotiated resources):
    #AddHandler type-map var

    #
    # Filters allow you to process content before it is sent to the client.
    #
    # To parse .shtml files for server-side includes (SSI):
    # (You will also need to add "Includes" to the "Options" directive.)
    #
    AddType text/html .shtml
    AddOutputFilter INCLUDES .shtml
</IfModule>

#
# Specify a default charset for all content served; this enables
# interpretation of all content as UTF-8 by default.  To use the 
# default browser choice (ISO-8859-1), or to allow the META tags
# in HTML content to override this choice, comment out this
# directive:
#
AddDefaultCharset UTF-8

<IfModule mime_magic_module>
    #
    # The mod_mime_magic module allows the server to use various hints from the
    # contents of the file itself to determine its type.  The MIMEMagicFile
    # directive tells the module where the hint definitions are located.
    #
    MIMEMagicFile conf/magic
</IfModule>

#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#

#
# EnableMMAP and EnableSendfile: On systems that support it, 
# memory-mapping or the sendfile syscall may be used to deliver
# files.  This usually improves server performance, but must
# be turned off when serving from networked-mounted 
# filesystems or if support for these functions is otherwise
# broken on your system.
# Defaults if commented: EnableMMAP On, EnableSendfile Off
#
#EnableMMAP off
EnableSendfile on

# Supplemental configuration
#
# Load config files in the "/etc/httpd/conf.d" directory, if any.
IncludeOptional conf.d/*.conf

2.4.3.2 phpldapadmin.conf
vi /etc/httpd/conf.d/phpldapadmin.conf
#
#  Web-based tool for managing LDAP servers
#

Alias /phpldapadmin /usr/share/phpldapadmin/htdocs
Alias /ldapadmin /usr/share/phpldapadmin/htdocs

<Directory /usr/share/phpldapadmin/htdocs>
  <IfModule mod_authz_core.c>
    # Apache 2.4
    Require all granted
  </IfModule>
  <IfModule !mod_authz_core.c>
    # Apache 2.2
    Order Deny,Allow
    Deny from all
    Allow from 127.0.0.1
    Allow from ::1
  </IfModule>
</Directory>

2.4.3.3 config.php
vi /etc/phpldapadmin/config.php
<?php
/** NOTE **
 ** Make sure that <?php is the FIRST line of this file!
 ** IE: There should NOT be any blank lines or spaces BEFORE <?php
 **/

/**
 * The phpLDAPadmin config file
 * See: http://phpldapadmin.sourceforge.net/wiki/index.php/Config.php
 *
 * This is where you can customise some of the phpLDAPadmin defaults
 * that are defined in config_default.php.
 *
 * To override a default, use the $config->custom variable to do so.
 * For example, the default for defining the language in config_default.php
 *
 * $this->default->appearance['language'] = array(
 *  'desc'=>'Language',
 *  'default'=>'auto');
 *
 * to override this, use $config->custom->appearance['language'] = 'en_EN';
 *
 * This file is also used to configure your LDAP server connections.
 *
 * You must specify at least one LDAP server there. You may add
 * as many as you like. You can also specify your language, and
 * many other options.
 *
 * NOTE: Commented out values in this file prefixed by //, represent the
 * defaults that have been defined in config_default.php.
 * Commented out values prefixed by #, dont reflect their default value, you can
 * check config_default.php if you want to see what the default is.
 *
 * DONT change config_default.php, you changes will be lost by the next release
 * of PLA. Instead change this file - as it will NOT be replaced by a new
 * version of phpLDAPadmin.
 */

/*********************************************
 * Useful important configuration overrides  *
 *********************************************/

/* If you are asked to put PLA in debug mode, this is how you do it: */
#  $config->custom->debug['level'] = 255;
#  $config->custom->debug['syslog'] = true;
#  $config->custom->debug['file'] = '/tmp/pla_debug.log';

/* phpLDAPadmin can encrypt the content of sensitive cookies if you set this
   to a big random string. */
$config->custom->session['blowfish'] = 'a0575c70d6f7ccdcb18b9e74921f9758';  # Autogenerated for node01

/* If your auth_type is http, you can override your HTTP Authentication Realm. */
// $config->custom->session['http_realm'] = sprintf('%s %s',app_name(),'login');

/* The language setting. If you set this to 'auto', phpLDAPadmin will attempt
   to determine your language automatically.
   If PLA doesnt show (all) strings in your language, then you can do some
   translation at http://translations.launchpad.net/phpldapadmin and download
   the translation files, replacing those provided with PLA.
   (We'll pick up the translations before making the next release too!) */
// $config->custom->appearance['language'] = 'auto';

/* The temporary storage directory where we will put jpegPhoto data
   This directory must be readable and writable by your web server. */
// $config->custom->jpeg['tmpdir'] = '/tmp';     // Example for Unix systems
#  $config->custom->jpeg['tmpdir'] = 'c:\\temp'; // Example for Windows systems

/* Set this to (bool)true if you do NOT want a random salt used when
   calling crypt().  Instead, use the first two letters of the user's
   password.  This is insecure but unfortunately needed for some older
   environments. */
#  $config->custom->password['no_random_crypt_salt'] = true;

/* PHP script timeout control. If php runs longer than this many seconds then
   PHP will stop with an Maximum Execution time error. Increase this value from
   the default if queries to your LDAP server are slow. The default is either
   30 seconds or the setting of max_exection_time if this is null. */
// $config->custom->session['timelimit'] = 30;

// $config->custom->appearance['show_clear_password'] = false;

// $config->custom->search['size_limit'] = 50;
#  $config->custom->search['size_limit'] = 1000;

/* Our local timezone
   This is to make sure that when we ask the system for the current time, we
   get the right local time. If this is not set, all time() calculations will
   assume UTC if you have not set PHP date.timezone. */
// $config->custom->appearance['timezone'] = null;
#  $config->custom->appearance['timezone'] = 'Australia/Melbourne';

/*********************************************
 * Commands                                  *
 *********************************************/

/* Command availability ; if you don't authorize a command the command
   links will not be shown and the command action will not be permitted.
   For better security, set also ACL in your ldap directory. */
/*
$config->custom->commands['cmd'] = array(
	'entry_internal_attributes_show' => true,
	'entry_refresh' => true,
	'oslinks' => true,
	'switch_template' => true
);

$config->custom->commands['script'] = array(
	'add_attr_form' => true,
	'add_oclass_form' => true,
	'add_value_form' => true,
	'collapse' => true,
	'compare' => true,
	'compare_form' => true,
	'copy' => true,
	'copy_form' => true,
	'create' => true,
	'create_confirm' => true,
	'delete' => true,
	'delete_attr' => true,
	'delete_form' => true,
	'draw_tree_node' => true,
	'expand' => true,
	'export' => true,
	'export_form' => true,
	'import' => true,
	'import_form' => true,
	'login' => true,
	'logout' => true,
	'login_form' => true,
	'mass_delete' => true,
	'mass_edit' => true,
	'mass_update' => true,
	'modify_member_form' => true,
	'monitor' => true,
	'purge_cache' => true,
	'query_engine' => true,
	'rename' => true,
	'rename_form' => true,
	'rdelete' => true,
	'refresh' => true,
	'schema' => true,
	'server_info' => true,
	'show_cache' => true,
	'template_engine' => true,
	'update_confirm' => true,
	'update' => true
);
*/

/*********************************************
 * Appearance                                *
 *********************************************/

/* If you want to choose the appearance of the tree, specify a class name which
   inherits from the Tree class. */
// $config->custom->appearance['tree'] = 'AJAXTree';
#  $config->custom->appearance['tree'] = 'HTMLTree';

/* Just show your custom templates. */
// $config->custom->appearance['custom_templates_only'] = false;

/* Disable the default template. */
// $config->custom->appearance['disable_default_template'] = false;

/* Hide the warnings for invalid objectClasses/attributes in templates. */
// $config->custom->appearance['hide_template_warning'] = false;

/* Set to true if you would like to hide header and footer parts. */
// $config->custom->appearance['minimalMode'] = false;

/* Configure what objects are shown in left hand tree */
// $config->custom->appearance['tree_filter'] = '(objectclass=*)';

/* The height and width of the tree. If these values are not set, then
   no tree scroll bars are provided. */
// $config->custom->appearance['tree_height'] = null;
#  $config->custom->appearance['tree_height'] = 600;
// $config->custom->appearance['tree_width'] = null;
#  $config->custom->appearance['tree_width'] = 250;

/* Confirm create and update operations, allowing you to review the changes
   and optionally skip attributes during the create/update operation. */
// $config->custom->confirm['create'] = true;
// $config->custom->confirm['update'] = true;

/* Confirm copy operations, and treat them like create operations. This allows
   you to edit the attributes (thus changing any that might conflict with
   uniqueness) before creating the new entry. */
// $config->custom->confirm['copy'] = true;

/*********************************************
 * User-friendly attribute translation       *
 *********************************************/

/* Use this array to map attribute names to user friendly names. For example, if
   you don't want to see "facsimileTelephoneNumber" but rather "Fax". */
// $config->custom->appearance['friendly_attrs'] = array();
$config->custom->appearance['friendly_attrs'] = array(
	'facsimileTelephoneNumber' => 'Fax',
	'gid'                      => 'Group',
	'mail'                     => 'Email',
	'telephoneNumber'          => 'Telephone',
	'uid'                      => 'User Name',
	'userPassword'             => 'Password'
);

/*********************************************
 * Hidden attributes                         *
 *********************************************/

/* You may want to hide certain attributes from being edited. If you want to
   hide attributes from the user, you should use your LDAP servers ACLs.
   NOTE: The user must be able to read the hide_attrs_exempt entry to be
   excluded. */
// $config->custom->appearance['hide_attrs'] = array();
#  $config->custom->appearance['hide_attrs'] = array('objectClass');

/* Members of this list will be exempt from the hidden attributes. */
// $config->custom->appearance['hide_attrs_exempt'] = null;
#  $config->custom->appearance['hide_attrs_exempt'] = 'cn=PLA UnHide,ou=Groups,c=AU';

/*********************************************
 * Read-only attributes                      *
 *********************************************/

/* You may want to phpLDAPadmin to display certain attributes as read only,
   meaning that users will not be presented a form for modifying those
   attributes, and they will not be allowed to be modified on the "back-end"
   either. You may configure this list here:
   NOTE: The user must be able to read the readonly_attrs_exempt entry to be
   excluded. */
// $config->custom->appearance['readonly_attrs'] = array();

/* Members of this list will be exempt from the readonly attributes. */
// $config->custom->appearance['readonly_attrs_exempt'] = null;
#  $config->custom->appearance['readonly_attrs_exempt'] = 'cn=PLA ReadWrite,ou=Groups,c=AU';

/*********************************************
 * Group attributes                          *
 *********************************************/

/* Add "modify group members" link to the attribute. */
// $config->custom->modify_member['groupattr'] = array('member','uniqueMember','memberUid');

/* Configure filter for member search. This only applies to "modify group members" feature */
// $config->custom->modify_member['filter'] = '(objectclass=Person)';

/* Attribute that is added to the group member attribute. */
// $config->custom->modify_member['attr'] = 'dn';

/* For Posix attributes */
// $config->custom->modify_member['posixattr'] = 'uid';
// $config->custom->modify_member['posixfilter'] = '(uid=*)';
// $config->custom->modify_member['posixgroupattr'] = 'memberUid';

/*********************************************
 * Support for attrs display order           *
 *********************************************/

/* Use this array if you want to have your attributes displayed in a specific
   order. You can use default attribute names or their fridenly names.
   For example, "sn" will be displayed right after "givenName". All the other
   attributes that are not specified in this array will be displayed after in
   alphabetical order. */
// $config->custom->appearance['attr_display_order'] = array();
#  $config->custom->appearance['attr_display_order'] = array(
#   'givenName',
#   'sn',
#   'cn',
#   'displayName',
#   'uid',
#   'uidNumber',
#   'gidNumber',
#   'homeDirectory',
#   'mail',
#   'userPassword'
#  );

/*********************************************
 * Define your LDAP servers in this section  *
 *********************************************/

$servers = new Datastore();

/* $servers->NewServer('ldap_pla') must be called before each new LDAP server
   declaration. */
$servers->newServer('ldap_pla');

/* A convenient name that will appear in the tree viewer and throughout
   phpLDAPadmin to identify this LDAP server to users. */
$servers->setValue('server','name','Local LDAP Server');

/* Examples:
   'ldap.example.com',
   'ldaps://ldap.example.com/',
   'ldapi://%2fusr%local%2fvar%2frun%2fldapi'
           (Unix socket at /usr/local/var/run/ldap) */
// $servers->setValue('server','host','127.0.0.1');

/* The port your LDAP server listens on (no quotes). 389 is standard. */
// $servers->setValue('server','port',389);

/* Array of base DNs of your LDAP server. Leave this blank to have phpLDAPadmin
   auto-detect it for you. */
// $servers->setValue('server','base',array(''));

/* Five options for auth_type:
   1. 'cookie': you will login via a web form, and a client-side cookie will
      store your login dn and password.
   2. 'session': same as cookie but your login dn and password are stored on the
      web server in a persistent session variable.
   3. 'http': same as session but your login dn and password are retrieved via
      HTTP authentication.
   4. 'config': specify your login dn and password here in this config file. No
      login will be required to use phpLDAPadmin for this server.
   5. 'sasl': login will be taken from the webserver's kerberos authentication.
      Currently only GSSAPI has been tested (using mod_auth_kerb).

   Choose wisely to protect your authentication information appropriately for
   your situation. If you choose 'cookie', your cookie contents will be
   encrypted using blowfish and the secret your specify above as
   session['blowfish']. */
// $servers->setValue('login','auth_type','session');

/* The DN of the user for phpLDAPadmin to bind with. For anonymous binds or
   'cookie','session' or 'sasl' auth_types, LEAVE THE LOGIN_DN AND LOGIN_PASS
   BLANK. If you specify a login_attr in conjunction with a cookie or session
   auth_type, then you can also specify the bind_id/bind_pass here for searching
   the directory for users (ie, if your LDAP server does not allow anonymous
   binds. */
// $servers->setValue('login','bind_id','');
#  $servers->setValue('login','bind_id','cn=Manager,dc=example,dc=com');

/* Your LDAP password. If you specified an empty bind_id above, this MUST also
   be blank. */
// $servers->setValue('login','bind_pass','');
#  $servers->setValue('login','bind_pass','secret');

/* Use TLS (Transport Layer Security) to connect to the LDAP server. */
// $servers->setValue('server','tls',false);

/************************************
 *      SASL Authentication         *
 ************************************/

/* Enable SASL authentication LDAP SASL authentication requires PHP 5.x
   configured with --with-ldap-sasl=DIR. If this option is disabled (ie, set to
   false), then all other sasl options are ignored. */
// $servers->setValue('login','auth_type','sasl');

/* SASL auth mechanism */
// $servers->setValue('sasl','mech','GSSAPI');

/* SASL authentication realm name */
// $servers->setValue('sasl','realm','');
#  $servers->setValue('sasl','realm','EXAMPLE.COM');

/* SASL authorization ID name
   If this option is undefined, authorization id will be computed from bind DN,
   using authz_id_regex and authz_id_replacement. */
// $servers->setValue('sasl','authz_id', null);

/* SASL authorization id regex and replacement
   When authz_id property is not set (default), phpLDAPAdmin will try to
   figure out authorization id by itself from bind distinguished name (DN).

   This procedure is done by calling preg_replace() php function in the
   following way:

   $authz_id = preg_replace($sasl_authz_id_regex,$sasl_authz_id_replacement,
    $bind_dn);

   For info about pcre regexes, see:
   - pcre(3), perlre(3)
   - http://www.php.net/preg_replace */
// $servers->setValue('sasl','authz_id_regex',null);
// $servers->setValue('sasl','authz_id_replacement',null);
#  $servers->setValue('sasl','authz_id_regex','/^uid=([^,]+)(.+)/i');
#  $servers->setValue('sasl','authz_id_replacement','$1');

/* SASL auth security props.
   See http://beepcore-tcl.sourceforge.net/tclsasl.html#anchor5 for explanation. */
// $servers->setValue('sasl','props',null);

/* Default password hashing algorithm. One of md5, ssha, sha, md5crpyt, smd5,
   blowfish, crypt or leave blank for now default algorithm. */
// $servers->setValue('appearance','pla_password_hash','md5');
$servers->setValue('appearance','pla_password_hash','');

/* If you specified 'cookie' or 'session' as the auth_type above, you can
   optionally specify here an attribute to use when logging in. If you enter
   'uid' and login as 'dsmith', phpLDAPadmin will search for (uid=dsmith)
   and log in as that user.
   Leave blank or specify 'dn' to use full DN for logging in. Note also that if
   your LDAP server requires you to login to perform searches, you can enter the
   DN to use when searching in 'bind_id' and 'bind_pass' above. */
// $servers->setValue('login','attr','dn');
// $servers->setValue('login','attr','uid');
// DATALIGHT
$servers->setValue('login','attr','cn');

/* Base DNs to used for logins. If this value is not set, then the LDAP server
   Base DNs are used. */
// $servers->setValue('login','base',array());

/* If 'login,attr' is used above such that phpLDAPadmin will search for your DN
   at login, you may restrict the search to a specific objectClasses. EG, set this
   to array('posixAccount') or array('inetOrgPerson',..), depending upon your
   setup. */
// $servers->setValue('login','class',array());

/* If you specified something different from 'dn', for example 'uid', as the
   login_attr above, you can optionally specify here to fall back to
   authentication with dn.
   This is useful, when users should be able to log in with their uid, but
   the ldap administrator wants to log in with his root-dn, that does not
   necessarily have the uid attribute.
   When using this feature, login_class is ignored. */
// $servers->setValue('login','fallback_dn',false);

/* Specify true If you want phpLDAPadmin to not display or permit any
   modification to the LDAP server. */
// $servers->setValue('server','read_only',false);

/* Specify false if you do not want phpLDAPadmin to draw the 'Create new' links
   in the tree viewer. */
// $servers->setValue('appearance','show_create',true);

/* Set to true if you would like to initially open the first level of each tree. */
// $servers->setValue('appearance','open_tree',false);

/* This feature allows phpLDAPadmin to automatically determine the next
   available uidNumber for a new entry. */
// $servers->setValue('auto_number','enable',true);

/* The mechanism to use when finding the next available uidNumber. Two possible
   values: 'uidpool' or 'search'.
   The 'uidpool' mechanism uses an existing uidPool entry in your LDAP server to
   blindly lookup the next available uidNumber. The 'search' mechanism searches
   for entries with a uidNumber value and finds the first available uidNumber
   (slower). */
// $servers->setValue('auto_number','mechanism','search');

/* The DN of the search base when the 'search' mechanism is used above. */
#  $servers->setValue('auto_number','search_base','ou=People,dc=example,dc=com');

/* The minimum number to use when searching for the next available number
   (only when 'search' is used for auto_number. */
// $servers->setValue('auto_number','min',array('uidNumber'=>1000,'gidNumber'=>500));

/* If you set this, then phpldapadmin will bind to LDAP with this user ID when
   searching for the uidnumber. The idea is, this user id would have full
   (readonly) access to uidnumber in your ldap directory (the logged in user
   may not), so that you can be guaranteed to get a unique uidnumber for your
   directory. */
// $servers->setValue('auto_number','dn',null);

/* The password for the dn above. */
// $servers->setValue('auto_number','pass',null);

/* Enable anonymous bind login. */
// $servers->setValue('login','anon_bind',true);
// DATALIGHT
$servers->setValue('login','anon_bind',false);

/* Use customized page with prefix when available. */
#  $servers->setValue('custom','pages_prefix','custom_');

/* If you set this, then only these DNs are allowed to log in. This array can
   contain individual users, groups or ldap search filter(s). Keep in mind that
   the user has not authenticated yet, so this will be an anonymous search to
   the LDAP server, so make your ACLs allow these searches to return results! */
#  $servers->setValue('login','allowed_dns',array(
#   'uid=stran,ou=People,dc=example,dc=com',
#   '(&(gidNumber=811)(objectClass=groupOfNames))',
#   '(|(uidNumber=200)(uidNumber=201))',
#   'cn=callcenter,ou=Group,dc=example,dc=com'));

/* Set this if you dont want this LDAP server to show in the tree */
// $servers->setValue('server','visible',true);

/* Set this if you want to hide the base DNs that dont exist instead of
   displaying the message "The base entry doesnt exist, create it?"
// $servers->setValue('server','hide_noaccess_base',false);
#  $servers->setValue('server','hide_noaccess_base',true);

/* This is the time out value in minutes for the server. After as many minutes
   of inactivity you will be automatically logged out. If not set, the default
   value will be ( session_cache_expire()-1 ) */
#  $servers->setValue('login','timeout',30);

/* Set this if you want phpldapadmin to perform rename operation on entry which
   has children. Certain servers are known to allow it, certain are not. */
// $servers->setValue('server','branch_rename',false);

/* If you set this, then phpldapadmin will show these attributes as
   internal attributes, even if they are not defined in your schema. */
// $servers->setValue('server','custom_sys_attrs',array(''));
#  $servers->setValue('server','custom_sys_attrs',array('passwordExpirationTime','passwordAllowChangeTime'));

/* If you set this, then phpldapadmin will show these attributes on
   objects, even if they are not defined in your schema. */
// $servers->setValue('server','custom_attrs',array(''));
#  $servers->setValue('server','custom_attrs',array('nsRoleDN','nsRole','nsAccountLock'));

/* These attributes will be forced to MAY attributes and become option in the
   templates. If they are not defined in the templates, then they wont appear
   as per normal template processing. You may want to do this because your LDAP
   server may automatically calculate a default value.
   In Fedora Directory Server using the DNA Plugin one could ignore uidNumber,
   gidNumber and sambaSID. */
// $servers->setValue('server','force_may',array(''));
#  $servers->setValue('server','force_may',array('uidNumber','gidNumber','sambaSID'));

/*********************************************
 * Unique attributes                         *
 *********************************************/

/* You may want phpLDAPadmin to enforce some attributes to have unique values
   (ie: not belong to other entries in your tree. This (together with
   'unique','dn' and 'unique','pass' option will not let updates to
   occur with other attributes have the same value. */
#  $servers->setValue('unique','attrs',array('mail','uid','uidNumber'));
// DATALIGHT
$servers->setValue('unique','attrs',array('mail','uid','uidNumber','cn','sn'));
/* If you set this, then phpldapadmin will bind to LDAP with this user ID when
   searching for attribute uniqueness. The idea is, this user id would have full
   (readonly) access to your ldap directory (the logged in user may not), so
   that you can be guaranteed to get a unique uidnumber for your directory. */
// $servers->setValue('unique','dn',null);

/* The password for the dn above. */
// $servers->setValue('unique','pass',null);

/**************************************************************************
 * If you want to configure additional LDAP servers, do so below.         *
 * Remove the commented lines and use this section as a template for all  *
 * your other LDAP servers.                                               *
 **************************************************************************/

/*
$servers->newServer('ldap_pla');
$servers->setValue('server','name','LDAP Server');
$servers->setValue('server','host','127.0.0.1');
$servers->setValue('server','port',389);
$servers->setValue('server','base',array(''));
$servers->setValue('login','auth_type','cookie');
$servers->setValue('login','bind_id','');
$servers->setValue('login','bind_pass','');
$servers->setValue('server','tls',false);

# SASL auth
$servers->setValue('login','auth_type','sasl');
$servers->setValue('sasl','mech','GSSAPI');
$servers->setValue('sasl','realm','EXAMPLE.COM');
$servers->setValue('sasl','authz_id',null);
$servers->setValue('sasl','authz_id_regex','/^uid=([^,]+)(.+)/i');
$servers->setValue('sasl','authz_id_replacement','$1');
$servers->setValue('sasl','props',null);

$servers->setValue('appearance','pla_password_hash','md5');
$servers->setValue('login','attr','dn');
$servers->setValue('login','fallback_dn',false);
$servers->setValue('login','class',null);
$servers->setValue('server','read_only',false);
$servers->setValue('appearance','show_create',true);

$servers->setValue('auto_number','enable',true);
$servers->setValue('auto_number','mechanism','search');
$servers->setValue('auto_number','search_base',null);
$servers->setValue('auto_number','min',array('uidNumber'=>1000,'gidNumber'=>500));
$servers->setValue('auto_number','dn',null);
$servers->setValue('auto_number','pass',null);

$servers->setValue('login','anon_bind',true);
$servers->setValue('custom','pages_prefix','custom_');
$servers->setValue('unique','attrs',array('mail','uid','uidNumber'));
$servers->setValue('unique','dn',null);
$servers->setValue('unique','pass',null);

$servers->setValue('server','visible',true);
$servers->setValue('login','timeout',30);
$servers->setValue('server','branch_rename',false);
$servers->setValue('server','custom_sys_attrs',array('passwordExpirationTime','passwordAllowChangeTime'));
$servers->setValue('server','custom_attrs',array('nsRoleDN','nsRole','nsAccountLock'));
$servers->setValue('server','force_may',array('uidNumber','gidNumber','sambaSID'));
*/
?>
2.4.4 启动 httpd 服务
systemctl start httpd
systemctl enable httpd
2.4.5 访问页面
http://node01:8007/phpldapadmin/

在这里插入图片描述

在这里插入图片描述

2.5 配置 LDAP 监控

2.5.1 下载 LDAP Exporter
https://github.com/tomcz/openldap_exporter/releases

三、SSSD

3.1 下载 SSSD 资源包

mkdir -p /data/install/SSSD/sssd-package

# 全量下载(推荐)
repotrack -p /data/install/SSSD/sssd-package sssd
# 增量下载(可能不适用于离线环境)
yumdownloader --resolve --destdir=/data/install/SSSD/sssd-package sssd

3.2 安装 SSSD

cd /data/install/SSSD/sssd-package

yum -y localinstall ./*.rpm --disablerepo='*'

3.3 配置 SSSD

3.3.1 编辑 sssd.conf 配置文件
vi /etc/sssd/sssd.conf
[sssd]
services = nss, pam
config_file_version = 2
domains = DATALIGHT
debug_level = 6

[domain/DATALIGHT]
id_provider = ldap
auth_provider = krb5
chpass_provider = krb5
ldap_uri = ldap://node01
ldap_search_base = dc=datalight,dc=com
krb5_server = node01
krb5_realm = DATALIGHT
access_provider = simple
simple_allow_users = root

[nss]
# Remove filter_users and filter_groups if root needs access
filter_users = root
filter_groups = root

[pam]
vi /etc/pam.d/password-auth-ac
#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth        required      pam_env.so
auth        required      pam_faildelay.so delay=2000000
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 1000 quiet_success
auth        sufficient    pam_sss.so use_first_pass
auth        required      pam_deny.so

account     required      pam_unix.so
account     sufficient    pam_localuser.so
account     [default=bad success=ok user_unknown=ignore] pam_sss.so
account     sufficient    pam_succeed_if.so uid < 1000 quiet
account     required      pam_permit.so

password    requisite     pam_pwquality.so try_first_pass local_users_only retry=3 authtok_type=
password    sufficient    pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    sufficient    pam_sss.so use_authtok
# password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
-session    optional      pam_systemd.so
session     required      pam_unix.so
session     optional      pam_sss.so
session     required      pam_mkhomedir.so skel=/etc/skel/ umask=0077
3.3.2 设置权限
chmod 600 /etc/sssd/sssd.conf
3.3.3 启动并启用 SSSD
systemctl start sssd
systemctl enable sssd
3.3.4 验证 SSSD
id datalight
3.3.5 添加配置 PAM
# 可忽略
vi /etc/pam.d/system-auth 
auth        required      pam_sss.so
account     required      pam_sss.so
password    required      pam_sss.so
session     required      pam_mkhomedir.so skel=/etc/skel/ umask=0077
session     required      pam_sss.so
vi /etc/pam.d/password-auth
auth        required      pam_sss.so
account     required      pam_sss.so
password    required      pam_sss.so
session     required      pam_mkhomedir.so skel=/etc/skel/ umask=0077
session     required      pam_sss.so
3.3.6 配置用户目录模板
cd /etc/skel
3.3.6.1 创建修改 .bashrc
vi /etc/skel/.bashrc
# .bashrc

# User specific aliases and functions

alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'

# Source global definitions
if [ -f /etc/bashrc ]; then
        . /etc/bashrc
fi

# source /etc/profile
3.3.6.2 创建修改 .bash_profile
vi /etc/skel/.bash_profile
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
        . ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/bin

export PATH

# source /etc/profile
3.3.6.3 验证文件存在
ls -la /etc/skel

四、添加用户

4.1 批量添加本地已存在用户

#!/bin/bash

# LDAP 管理员的 DN 和密码
LDAP_ADMIN_DN="${LDAP_ADMIN_DN:-cn=admin,dc=datalight,dc=com}"
LDAP_ADMIN_PASS="${LDAP_ADMIN_PASS:-123456}"

# LDAP 服务器地址
LDAP_SERVER="${LDAP_SERVER:-ldap://node01}"

# 日志文件位置
LOG_FILE="/var/log/ldap_sync.log"

# 检查依赖项
function check_dependencies() {
    if ! command -v slappasswd &> /dev/null; then
        echo "Error: slappasswd is not installed." >&2
        exit 1
    fi
}

# 写入日志
function log() {
    local message="$1"
    echo "$(date '+%Y-%m-%d %H:%M:%S') $message" >> "$LOG_FILE"
}

# 获取本地用户列表并排除系统用户
function get_local_users() {
    awk -F: '$3 >= 1000 { print $1 }' /etc/passwd
}

# 生成用户的密码哈希
function generate_password_hash() {
    local password="$1"
    slappasswd -s "$password"
}

# 创建 LDIF 条目
function create_ldif_entry() {
    local user="$1"
    local password_hash="$2"
    cat <<EOF
dn: uid=$user,dc=datalight,dc=com
objectClass: inetOrgPerson
objectClass: posixAccount
objectClass: top
cn: $user
sn: $user
uid: $user
uidNumber: $(id -u $user)
gidNumber: $(id -g $user)
homeDirectory: /home/$user
loginShell: /bin/bash
userPassword: $password_hash
EOF
}

# 主函数
function main() {
    check_dependencies

    log "Starting LDAP synchronization."

    # 获取本地用户列表
    LOCAL_USERS=$(get_local_users)

    # 遍历每个本地用户
    for USER in $LOCAL_USERS; do
        # 生成用户的密码哈希
        # PASSWORD_HASH=$(generate_password_hash "12345678")
        PASSWORD_HASH="{SSHA}Zyva6dgyEZmcBLBic7aP/ba/LEgORIO8"

        # 创建 LDIF 条目
        LDIF_ENTRY=$(create_ldif_entry "$USER" "$PASSWORD_HASH")

        # 将用户添加到 LDAP
        echo "$LDIF_ENTRY" | ldapadd -x -D "$LDAP_ADMIN_DN" -w "$LDAP_ADMIN_PASS" -H "$LDAP_SERVER" || {
            log "Failed to add user $USER to LDAP."
            continue
        }

        log "User $USER added to LDAP successfully."
    done

    log "LDAP synchronization completed."
}

main

4.2 逐个添加本地用户

4.2.1 创建用户 LDIF 文件
vi ~/alice.ldif
dn: uid=alice,dc=datalight,dc=com
objectClass: inetOrgPerson
objectClass: posixAccount
objectClass: top

cn: alice
sn: alice
uid: alice
uidNumber: 1001
gidNumber: 1000
homeDirectory: /home/alice
loginShell: /bin/bash
userPassword: {SSHA}Zyva6dgyEZmcBLBic7aP/ba/LEgORIO8
ldapadd -x -D "cn=admin,dc=datalight,dc=com" -W -f ~/alice.ldif

# 删除:
ldapdelete -x -D "cn=admin,dc=datalight,dc=com" -W "uid=alice,dc=datalight,dc=com"
4.2.2 修改用户组
vi ~/modify-alice.ldif
dn: uid=alice,dc=datalight,dc=com
changetype: modify
replace: gidNumber
gidNumber: 1000
ldapmodify -x -D "cn=admin,dc=datalight,dc=com" -W -f modify-alice.ldif
4.4.3 清除 SSSD 缓存
sss_cache -E

4.3 创建 Kerberos 主体

kadmin.local -q "addprinc datalight@DATALIGHT"

五、修改默认日志目录

5.1 修改 Kerberos 日志目录

5.1.1 修改 KDC 日志目录
vi /etc/krb5.conf
[logging]
 default = FILE:/data/datalight/logs/KERBEROS/krb5libs.log
 kdc = FILE:/data/datalight/logs/KERBEROS/krb5kdc.log
 admin_server = FILE:/data/datalight/logs/KERBEROS/kadmind.log
systemctl restart krb5kdc
systemctl restart kadmin

5.2 修改 LDAP 日志目录

vi /etc/rsyslog.conf
# 指定 LDAP 日志文件的位置
local4.*    /data/datalight/logs/LDAP/ldap.log

创建修改:

vi ~/ldap-loglevel.ldif
dn: cn=config
changetype: modify
replace: olcLogLevel
olcLogLevel: 256
ldapmodify -x -D "cn=admin,dc=datalight,dc=com" -w 123456 -H ldap://node01 -f ~/modify-log-level.ldif
systemctl restart rsyslog
systemctl restart slapd

5.3 修改 SSSD 日志目录

5.3.1 修改配置文件路径
ln -s /var/log/sssd /data/datalight/logs/SSSD/sssd

六、卸载

6.1 停止服务

6.1.1 停止 Kerberos 服务
systemctl stop krb5kdc
systemctl stop kadmin
systemctl disable krb5kdc
systemctl disable kadmin
6.1.2 停止 LDAP 服务
systemctl stop slapd
systemctl disable slapd
6.1.3 停止 SSSD 服务
systemctl stop sssd
systemctl disable sssd

6.2 卸载软件包

6.2.1 卸载 Kerberos
yum -y remove krb5-server krb5-workstation
6.2.2 卸载 LDAP
yum -y remove compat-openldap openldap-clients openldap-servers openldap-servers-sql openldap-devel

rm -rf /etc/openldap
rm -rf /var/lib/ldap

userdel ldap
6.2.3 卸载 SSSD
yum -y remove sssd

关注我们


感谢您一直以来对 DataLight 的支持和信任。DataLight 将为您带来更加智能和高效的数据管理体验。期待您的使用和反馈!
——DataLight 团队


关注我们,获取更多最新资讯:

微信公众号:

在这里插入图片描述

QQ 交流群:

在这里插入图片描述

微信交流:

在这里插入图片描述

一起见证数据世界的无限可能!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值