728x90
반응형

개요

LDAP을 사용 중인 사용자들에게 

보안정책에 따라 패스워드 만료일이 다가오거나 만료가 되었을 때

메일로 알려주는 역할을 한다.

메일 문구는 예씨로 작성 하였다. 자유롭게 변경 가능하다.

MY_LDAP_HOSTURI="ldapi:///"
MY_LDAP_DEFAULTPWDPOLICYDN="cn=default,ou=Policies,cn=manager,dc=test,dc=com"
MY_LDAP_EXCLUDEPWDPOLICYDN="cn=e,cn=default,ou=Policies,cn=manager,dc=test,dc=com"
MY_LDAP_SEARCHBASE="ou=People,dc=test,dc=com"
MY_LDAP_SEARCHFILTER="(&(uid=*)(objectClass=inetOrgPerson))"
MY_LDAP_SEARCHSCOPE="one"
MY_LDAP_SEARCHBIN="/usr/bin/ldapsearch"
#MY_MAIL_DELAY=10
MY_LDAP_NAME_ATTR=cn
MY_LDAP_LOGIN_ATTR=uid
MY_LDAP_MAIL_ATTR=mail
export LC_ALL=ko_KR.UTF-8
MY_MAIL_BODY="
        안녕하세요 %name 님,\n\n \

        귀하의 비밀번호 변경이 필요합니다. \n\n \

        해당 비밀번호는 정보보호 정책에 의해 %expireTimeTZ, %expireDays 일 후 만료 됩니다. \n\n \

        아래 해당 정책에 준수하여 변경 부탁드립니다.:\n\n \

        \t\t - 영문 대소문자/숫자/특수문자 중 3가지 이상 조합, 최소 8자리 이상 \n\n \
        \t\t - 비밀번호 변경 페이지  \n \
        \t\t    http://ssp.ldap.test.com/ \n\n \
        \t\t - 비밀번호 변경 후 공용폴더 사용자들은 Windows 자격증명 변경이 필요합니다. \n\n \
        \t\t - 아래 매뉴얼을 확인 하시어 Windows 자격증명을 변경 하세요.
        \t\t    

        추가로 문의사항은 Infra Part에 문의 바랍니다. \n\n \

        감사합니다."
EX_MAIL_BODY="
        안녕하세요 %name 님,\n\n \

        %name 님의 비밀번호가 %expireTimeTZ 부로 만료 되었습니다. \n\n \

        아래 주소로 접속하셔서 '패스워드 초기화' 를 진행하시기 바랍니다. \n\n \

        \t\t - 비밀번호 초기화 페이지 \n \
        \t\t    http://ssp.ldap.test.com/index.php?action=sendtoken \n\n \
        \t\t - 그룹웨어 메일 확인 필수 \n\n \
        \t\t - 비밀번호 초기화 후 공용폴더 사용자들은 Windows 자격증명 변경이 필요합니다. \n\n \
        \t\t - 아래 매뉴얼을 확인 하시어 Windows 자격증명을 변경 하세요.
        \t\t   

        추가 문의사항 있을 시 Infra Part에 문의 바랍니다. \n\n \

        감사합니다."
MY_MAIL_SUBJECT="[회사] 비밀번호 상태 안내 메일 입니다."
MY_MAIL_BIN="mail"
#MY_LOG_HEADER="`date +\"%b %e,%Y %T\"`"
MY_LOG_HEADER="`TZ='Asia/Seoul' date +\"%Y년 %B %d일 %A %T\"`"
MY_GAWK_BIN="/usr/bin/gawk"
getTimeInSeconds() {
        date=0
        os=`uname -s`
        if [ "$1" ]; then
                #date=`${MY_GAWK_BIN} 'BEGIN  { \
                date=`TZ=UTC ${MY_GAWK_BIN} 'BEGIN  { \
                        if (ARGC == 2) { \
                                print mktime(ARGV[1]) \
                        } \
                        exit 0 }' "$1"`
        else
                if [ "${os}" = "SunOS" ]; then
                        date=`/usr/bin/truss /usr/bin/date 2>&1 | nawk -F= \
                                '/^time\(\)/ {gsub(/ /,"",$2);print $2}'`
                else
                        now=`date +"%Y %m %d %H %M %S" -u`
                        #now=`date +"%Y %m %d %H %M %S"`
                        date=`getTimeInSeconds "$now"`
                fi
        fi
        echo ${date}
}
tmp_dir="/tmp/$$.checkldap.tmp"
result_file="${tmp_dir}/res.tmp.1"
buffer_file="${tmp_dir}/buf.tmp.1"
tmp_dir_stats="/tmp/ldap-password-stats"
ldap_param="-Y EXTERNAL -H ${MY_LDAP_HOSTURI} -LLL -Q"
nb_users=0
nb_expired_users=0
nb_warning_users=0
nb_exclude_users=0
if [ -d ${tmp_dir} ]; then
        echo "Error : temporary directory exists (${tmp_dir})"
        exit 1
fi
mkdir ${tmp_dir}
if [ ${MY_LDAP_ROOTDN} ]; then
        ldap_param="${ldap_param} -D ${MY_LDAP_ROOTDN} -w ${MY_LDAP_ROOTPW}"
fi
${MY_LDAP_SEARCHBIN} ${ldap_param} -s ${MY_LDAP_SEARCHSCOPE} \
        -b "${MY_LDAP_SEARCHBASE}" "${MY_LDAP_SEARCHFILTER}" \
        "dn" > ${result_file}
while read dnStr
do
        if [ ! "${dnStr}" ]; then
                continue
        fi
        dn=`echo ${dnStr} | cut -d : -f 2`
        nb_users=`expr ${nb_users} + 1`
        ${MY_LDAP_SEARCHBIN} ${ldap_param} -s base -b "${dn}" \
                ${MY_LDAP_NAME_ATTR} ${MY_LDAP_LOGIN_ATTR} ${MY_LDAP_MAIL_ATTR} pwdChangedTime pwdPolicySubentry \
                > ${buffer_file}
        login=`grep -w "${MY_LDAP_LOGIN_ATTR}:" ${buffer_file} | cut -d : -f 2 \
                | sed "s/^ *//;s/ *$//"`
        name=`grep -w "${MY_LDAP_NAME_ATTR}:" ${buffer_file} | cut -d : -f 2\
                | sed "s/^ *//;s/ *$//"`
        name2=`echo ${name}`
        mail=`grep -w "${MY_LDAP_MAIL_ATTR}:" ${buffer_file} | cut -d : -f 2 \
                | sed "s/^ *//;s/ *$//"`
        pwdChangedTime=`grep -w "pwdChangedTime:" ${buffer_file} \
                | cut -d : -f 2 | cut -c 1-15 | sed "s/^ *//;s/ *$//"`
        pwdPolicySubentry=`grep -w "pwdPolicySubentry:" ${buffer_file} \
                | cut -d : -f 2 | sed "s/^ *//;s/ *$//"`
        if [ ! "${pwdChangedTime}" ]; then
                echo "${login} (${mail}) 해당 계정은 패스워드 변경 날짜가 존재하지 않습니다." >> ${tmp_dir_stats}
                continue
        fi
        if [ ! "${pwdPolicySubentry}" -a ! "${MY_LDAP_DEFAULTPWDPOLICYDN}" ]; then
                echo "${login} (${mail}) 해당 계정은 패스워드 정책이 걸려있지 않습니다." >> ${tmp_dir_stats}
                continue
        fi
        if [ "${pwdPolicySubentry}" ]; then
                echo "${login} (${mail}) 해당 계정은 패스워드 정책 제외 대상 입니다." >> ${tmp_dir_stats}
                continue
        fi
        ldap_search="${MY_LDAP_SEARCHBIN} ${ldap_param} -s base"
        if [ "${pwdPolicySubentry}" ]; then
                ldap_search="${ldap_search} -b ${pwdPolicySubentry}"
        else
                ldap_search="${ldap_search} -b ${MY_LDAP_DEFAULTPWDPOLICYDN}"
        fi
        ldap_search="$ldap_search pwdMaxAge pwdExpireWarning pwdMinLength pwdInHistory"
        pwdMaxAge=`${ldap_search} | grep -w "pwdMaxAge:" | cut -d : -f 2 \
                | sed "s/^ *//;s/ *$//"`
        pwdExpireWarning=`${ldap_search} | grep -w "pwdExpireWarning:" | cut -d : -f 2 \
                | sed "s/^ *//;s/ *$//"`
        pwdMinLength=`${ldap_search} | grep -w "pwdMinLength:" | cut -d : -f 2 \
                | sed "s/^ *//;s/ *$//"`
        pwdInHistory=`${ldap_search} | grep -w "pwdInHistory:" | cut -d : -f 2 \
                | sed "s/^ *//;s/ *$//"`
        if [ ! "${pwdMaxAge}" ]; then
                echo "${login} (${mail}) 해당 계정은 만료 설정이 되어 있지 않습니다." >> ${tmp_dir_stats}
                continue
        fi
        MY_MAIL_DELAY=${MY_MAIL_DELAY:=$pwdExpireWarning}
        if [ "${pwdChangedTime}" ]; then
                s=`echo ${pwdChangedTime} | cut -c 13-14`
                m=`echo ${pwdChangedTime} | cut -c 11-12`
                h=`echo ${pwdChangedTime} | cut -c 9-10`
                d=`echo ${pwdChangedTime} | cut -c 7-8`
                M=`echo ${pwdChangedTime} | cut -c 5-6`
                y=`echo ${pwdChangedTime} | cut -c 1-4`
                currentTime=`getTimeInSeconds`
                pwdChangedTime=`getTimeInSeconds "$y $M $d $h $m $s"`
                diffTime=`expr ${currentTime} - ${pwdChangedTime}`
        fi
        expireTime=`expr ${pwdChangedTime} + ${pwdMaxAge}`
        expireWarningTime=`expr ${pwdChangedTime} + ${MY_MAIL_DELAY}`
        if [ ${currentTime} -gt ${expireTime} ]; then
                nb_expired_users=`expr ${nb_expired_users} + 1`
                expireTime=`date -d @$expireTime "+%Y년 %B %d일 %A %T"`
                logmsg="${EX_MAIL_BODY}"
                logmsg=`echo -e ${logmsg} | sed "s/%name/${name}/; \
                        s/%login/${login}/; s/%expireTimeTZ/${expireTime}/; s/%pwdMinLength/${pwdMinLength}/; s/%pwdInHistory/${pwdInHistory}/; \
                        s/%expireDays/${expireDays}/"`
                #echo "${logmsg}" | ${MY_MAIL_BIN} -S "from=Infra Part <ldap>" -s "${MY_MAIL_SUBJECT}" ${mail} >&2
                echo "${logmsg}" | ${MY_MAIL_BIN} -S "from=Infra Part <ldap>" -s "${MY_MAIL_SUBJECT}" test@test.co.kr >&2
                echo "${login} 해당 계정이 ${expireTime} 부로 패스워드 정책에 의해 만료 되었습니다. ${mail} 해당 메일로 안내 메일이 발송 되었습니다." >> ${tmp_dir_stats}
                continue
        fi
        expireTimeTZ=`date -d @$expireTime "+%Y년 %B %d일 %A %T"`
        expireTimeMail=`date -d @$expireTime "+%s"`
        now=`date +%s`
        expireDays=`echo $(( (${expireTimeMail} - ${now} )/(60*60*24) ))`
        if [ "${mail}" -a "${name}" \
                -a "${login}" -a "${diffTime}" -a "${pwdMaxAge}" ]
        then
                diffTime=`expr ${diffTime} + ${MY_MAIL_DELAY}`
                #if [ ${diffTime} -gt ${pwdMaxAge} ]; then
                if [ ${currentTime} -gt ${expireWarningTime} -a ${currentTime} -lt ${expireTime} ]; then
                        logmsg="${MY_MAIL_BODY}"
                        logmsg=`echo -e ${logmsg} | sed "s/%name/${name}/; \
                                s/%login/${login}/; s/%expireTimeTZ/${expireTimeTZ}/; s/%pwdMinLength/${pwdMinLength}/; s/%pwdInHistory/${pwdInHistory}/; \
                                s/%expireDays/${expireDays}/"`
                        #echo "${logmsg}" | ${MY_MAIL_BIN} -S "from=Infra Part <ldap>" -s "${MY_MAIL_SUBJECT}" ${mail} >&2
                        echo "${logmsg}" | ${MY_MAIL_BIN} -S "from=Infra Part <ldap>" -s "${MY_MAIL_SUBJECT}" test@test.co.kr >&2
                        echo "${login} 해당 계정의 만료 날짜가 다가옵니다. ${mail} 해당 메일로 안내 발송 되었습니다. (만료 날짜, ${expireTimeTZ})." >> ${tmp_dir_stats}
                        nb_warning_users=`expr ${nb_warning_users} + 1`
                fi
        fi
done < ${result_file}
sed -i "1i관리자님,\n${MY_LOG_HEADER} 기준, 임직원 패스워드 상태 리스트 입니다.\n" ${tmp_dir_stats}
echo "Total 체크된 사용자: ${nb_users}" >> ${tmp_dir_stats}
echo "비밀번호 만료된 사용자: ${nb_expired_users}" >> ${tmp_dir_stats}
echo "비밀번호 만료 사전 안내된 사용자: ${nb_warning_users}" >> ${tmp_dir_stats}
sed -i -e '/^Total.*/i\\ ' -e '/^Total.*/i ===== 통계 =====' ${tmp_dir_stats}
#mail -S "from=Infra Part <ldap>" -s "[LDAP] 임직원 패스워드 만료 상태 리스트" infra_p@test.co.kr < ${tmp_dir_stats}
mail -S "from=Infra Part <ldap>" -s "[LDAP] 임직원 패스워드 만료 상태 리스트" t@test.co.kr < ${tmp_dir_stats}
rm -rf ${tmp_dir}
rm -rf ${tmp_dir_stats}
exit 0
728x90
300x250
728x90
반응형

개요

그룹웨어 User 테이블에서 사용자 정보를 불러와서,

LDAP에 자동으로 등록 처리 해주는 구문이다.

새로 추가되는 팀이 있다면, 사용자가 팀을 이동한다면 또한 자동 관리 된다.

 

해당 스크립을 ldap crontab에 등록 해주면 스케쥴링되어 자동으로 세팅 될 것이다.

#!/bin/bash
/usr/bin/python /usr/share/openldap-servers/userExports.py

sleep 50

cn=(`/usr/bin/cat /usr/share/openldap-servers/userList.json | jq .userid | cut -d\" -f2`)
uid=(`/usr/bin/cat /usr/share/openldap-servers/userList.json | jq .userid | cut -d\" -f2`)
sn=(`/usr/bin/cat /usr/share/openldap-servers/userList.json | jq .username | cut -d\" -f2`)
groupCode=(`/usr/bin/cat /usr/share/openldap-servers/userList.json | jq .deptcode | cut -d\" -f2`)
groupName=(`/usr/bin/cat /usr/share/openldap-servers/userList.json | jq .deptname | cut -d\" -f2 | sed 's/ //g'`)
mailaddr=(`/usr/bin/cat /usr/share/openldap-servers/userList.json | jq .mailaddr | cut -d\" -f2`)
userDeleteList=(`/usr/bin/cat /usr/share/openldap-servers/userStopList.json | jq .userid | cut -d\" -f2`)
/usr/bin/ldapsearch -xLLL -H ldap://IP_ADDRESS -b "ou=Group,dc=test,dc=com" | grep "cn:" | perl -MMIME::Base64 -MEncode=decode -n -00 -e 's/\n +//g;s/(?<=:: )(\S+)/decode("UTF-8",decode_base64($1))/eg;print' | awk '{print $2}' > /usr/share/openldap-servers/groupList.lst
groupList=(`/usr/bin/cat /usr/share/openldap-servers/groupList.lst`)
gwTotalGroupList=(`/usr/bin/cat /usr/share/openldap-servers/gwTotalGroupList.lst | jq .deptname | cut -d\" -f2`)
finalUID=
finalSN=
finalMail=

# 사용자 생성
userCreate() {
/usr/bin/cat > /usr/share/openldap-servers/userCreate.ldif <<EOF
dn: uid=${finalUID},ou=People,dc=test,dc=com
objectClass: posixAccount
objectClass: top
objectClass: inetOrgPerson
objectClass: sambaSamAccount
displayName: ${finalUID}
uid: ${finalUID}
homeDirectory: /home/${finalUID}
sambaKickoffTime: 2147483647
sambaAcctFlags: [U]
uidNumber: ${uidNumber}
sambaSID: ${sambaSID}
sambaDomainName: REFINEHUB.COM
sn: ${finalSN}
mail: ${finalMail}
cn: ${finalUID}
gidNumber: ${gidNumber}
sambaNTPassword: 4EFAB4E3D4DD4A1B5837C600E13F5794
sambaPwdLastSet: 1643023108
sambaPrimaryGroupSID: S-1-5-21-2943257643-222489679-77770093-16330
EOF
/usr/bin/ldapadd -x -D cn=manager,dc=test,dc=com -w Wjstkstlf12 -f /usr/share/openldap-servers/userCreate.ldif
verifyUser=`/usr/bin/ldapsearch -xLLL -H ldap://IP_ADDRESS -b "ou=People,dc=test,dc=com" "(&(uid=${finalUID}))" | grep "cn: " | cut -d: -f 2 | sed 's/^ //'`
if [[ -n ${verifyUser} ]]; then
    /usr/bin/ldappasswd -s Password\$710 -w Wjstkstlf12 -D cn=manager,dc=test,dc=com -x "uid=${finalUID},ou=People,dc=test,dc=com"
fi
}

# 팀에 사용자 추가
userAddInGroup(){
/usr/bin/cat > /usr/share/openldap-servers/userAddInGroup.ldif <<EOF
dn: cn=${groupName[$id]},ou=Group,dc=test,dc=com
changetype: modify
add: memberUid
memberUid: ${finalUID}
EOF
/usr/bin/ldapmodify -x -D cn=manager,dc=test,dc=com -w Wjstkstlf12 -f /usr/share/openldap-servers/userAddInGroup.ldif
}

# 새로운 팀을 생성
newGroupCreate(){
/usr/bin/cat > /usr/share/openldap-servers/newGroupCreate.ldif <<EOF
dn: cn=${groupName[$id]},ou=Group,dc=test,dc=com
objectClass: posixGroup
objectClass: top
objectClass: sambaGroupMapping
cn: ${groupName[$id]}
sambaGroupType: 2
displayName: ${groupName[$id]}
gidNumber: ${gidNumber}
sambaSID: ${sambaSID}
EOF
/usr/bin/ldapadd -x -D cn=manager,dc=test,dc=com -w Wjstkstlf12 -f /usr/share/openldap-servers/newGroupCreate.ldif
}

# GrafanaAdmin 같은 그룹웨어 통해 생성한 그룹이 아닌 LDAP 자체에서 생성한 임의의 그룹인지 비교 후 이전 그룹(팀)에서 사용자 삭제
deleteUserInGroup() {
gwGroupCompare2=`/usr/bin/cat /usr/share/openldap-servers/userList.json | jq .deptname | cut -d\" -f2 | sed 's/ //g' | grep ${groupName[$id]} | uniq`
gwGroupCompare=`/usr/bin/cat /usr/share/openldap-servers/gwTotalGroupList.lst | jq .deptname | cut -d\" -f2 | sed 's/ //g' | grep ${line}`
echo "deleteUserInGroup ${gwGroupCompare2} ${gwGroupCompare} ${uid[$id]} ${groupName[$id]}" >> /usr/share/openldap-servers/log
if [[ "${gwGroupCompare2}" != "${gwGroupCompare}" ]] && [[ -z "${gwGroupCompare}" ]]; then
/usr/bin/cat > /usr/share/openldap-servers/deleteUserInGroup.ldif <<EOF
dn: cn=${line},ou=Group,dc=test,dc=com
changetype: modify
delete: memberUid
memberUid: ${uid[$id]}
EOF
/usr/bin/ldapmodify -x -D cn=manager,dc=test,dc=com -w Wjstkstlf12 -f /usr/share/openldap-servers/deleteUserInGroup.ldif
fi
gwGroupCompare=""
}

# 새로운 팀에 해당 사용자를 추가
addUserInNewGroup(){
/usr/bin/cat > /usr/share/openldap-servers/addUserInNewGroup.ldif <<EOF
dn: cn=${groupName[$id]},ou=Group,dc=test,dc=com
changetype: modify
add: memberUid
memberUid: ${uid[$id]}
EOF
/usr/bin/ldapmodify -x -D cn=manager,dc=test,dc=com -w Wjstkstlf12 -f /usr/share/openldap-servers/addUserInNewGroup.ldif
}

for id in "${!groupName[@]}"; do 
    uidNumber=(`/usr/bin/cat /dev/urandom | tr -dc '0-9' | fold -w 6 | sed 1q`)
    sambaSID=S-1-5-21-2943257643-222489679-77770093-$(/usr/bin/cat /dev/urandom | tr -dc '0-9' | fold -w 5 | sed 1q)
    gidNumber=(`/usr/bin/cat /dev/urandom | tr -dc '0-9' | fold -w 6 | sed 1q`)
    #id2=`expr ${id} + 1`

    # LDAP 사용자의 무슨 팀인지 확인
    searchingGroupOfUser=`/usr/bin/ldapsearch -xLLL -H ldap://IP_ADDRESS -b "ou=Group,dc=test,dc=com" "(&(memberUid=${uid[$id]}))" | perl -MMIME::Base64 -MEncode=decode -n -00 -e 's/\n +//g;s/(?<=:: )(\S+)/decode("UTF-8",decode_base64($1))/eg;print' | grep "cn:" | cut -d: -f 3 | sed 's/^ //' > /usr/share/openldap-servers/searchingGroupOfUser.lst`
    
    # 팀이 바뀐 직원이 있는지 체크
    while read line; do
    #searchingLdapUser=`/usr/bin/ldapsearch -xLLL -H ldap://IP_ADDRESS -b "cn=${line},ou=Group,dc=test,dc=com" | perl -MMIME::Base64 -MEncode=decode -n -00 -e 's/\n +//g;s/(?<=:: )(\S+)/decode("UTF-8",decode_base64($1))/eg;print' | grep ${uid[$id]} | cut -d: -f 2 | sed 's/^ //'`
    if [[ "${line}" != "${groupName[$id]}" ]]; then
    #if [[ "${searchingLdapUser}" != "${groupName[$id]}" ]]; then
        deleteUserInGroup
        addUserInNewGroup
        else
            continue
    fi
    done < /usr/share/openldap-servers/searchingGroupOfUser.lst


    # LDAP 그룹 조회
    searchingGroupList=`/usr/bin/cat /usr/share/openldap-servers/groupList.lst | grep ${groupName[$id]}`

    # 사용자 생성 단계
    # 새로운 팀이 생긴 건지 아닌지 판단
    if [[ "${groupName[$id]}" == "${searchingGroupList}" ]]; then
            finalUID=${uid[$id]}
            finalSN=${sn[$id]}
            finalMail=${mailaddr[$id]}
            userCreate
            userAddInGroup
        else
    # 새로운 팀 추가
            newGroupCreate
            finalUID=${uid[$id]}
            finalSN=${sn[$id]}
            finalMail=${mailaddr[$id]}
            userCreate
            userAddInGroup
    fi

    #겸임 하는 사람에 대해 체크하여 1개 이상의 그룹을 갖도록 추가
    countGroupOfUser=`/usr/bin/cat /usr/share/openldap-servers/userList.json | jq .userid | cut -d\" -f2 | sed 's/ //g' | grep ${uid[$id]} | wc -l`
    if [[ ${countGroupOfUser} -gt 2 ]]; then
        echo "countGroupOfUser ${countGroupOfUser} ${uid[$id]} ${groupName[$id]}" >> /usr/share/openldap-servers/log
        addUserInNewGroup
        else
            continue
    fi

done

# 퇴사자가 있으면 삭제
for empno in "${!userDeleteList[@]}"; do
/usr/bin/ldapsearch -xLLL -H ldap://IP_ADDRESS -b "ou=Group,dc=test,dc=com" "(&(memberUid=${userDeleteList[empno]}))" | perl -MMIME::Base64 -MEncode=decode -n -00 -e 's/\n +//g;s/(?<=:: )(\S+)/decode("UTF-8",decode_base64($1))/eg;print' | grep "cn:" | cut -d: -f 3 | sed 's/^ //' > /usr/share/openldap-servers/exitedUserInGroup.lst
exitedUserInGroup=`/usr/bin/cat /usr/share/openldap-servers/exitedUserInGroup.lst`
/usr/bin/cat > /usr/share/openldap-servers/exitedUserInGroup.ldif <<EOF
dn: cn=${exitedUserInGroup},ou=Group,dc=test,dc=com
changetype: modify
delete: memberUid
memberUid: ${userDeleteList[empno]}
EOF
/usr/bin/ldapmodify -x -D cn=manager,dc=test,dc=com -w Wjstkstlf12 -f /usr/share/openldap-servers/exitedUserInGroup.ldif
/usr/bin/ldapdelete -x -D cn=manager,dc=test,dc=com -w Wjstkstlf12 uid=${userDeleteList[empno]},ou=People,dc=test,dc=com
done
728x90
300x250
728x90
반응형

1. OpenLDAP 설치

yum install -y compat-openldap openldap openldap-servers openldap-clients openldap-servers-sql openldap-devel samba-common samba samba-client cifs-utils

2. OpenLDAP DB 설정

cp /usr/share/openldap-servers/DB_CONFIG.example /var/lib/ldap/DB_CONFIG
chown ldap. /var/lib/ldap/DB_CONFIG

3. 서비스 등록

systemctl --now enable slapd.service

4. 서비스 확인

systemctl status slapd.service
● slapd.service - OpenLDAP Server Daemon
   Loaded: loaded (/usr/lib/systemd/system/slapd.service; enabled; vendor preset: disabled)
   Active: active (running) since Fri 2021-06-11 16:23:18 KST; 22min ago
     Docs: man:slapd
           man:slapd-config
           man:slapd-hdb
           man:slapd-mdb
           file:///usr/share/doc/openldap-servers/guide.html
  Process: 7786 ExecStart=/usr/sbin/slapd -u ldap -h ${SLAPD_URLS} $SLAPD_OPTIONS (code=exited, status=0/SUCCESS)
  Process: 7757 ExecStartPre=/usr/libexec/openldap/check-config.sh (code=exited, status=0/SUCCESS)
 Main PID: 7789 (slapd)
   CGroup: /system.slice/slapd.service
           └─7789 /usr/sbin/slapd -u ldap -h ldapi:/// ldap:///
netstat -nlp | grep 389
ps -ef | grep -v grep | grep slapd

5. OpenLDAP 구성

slappasswd -h {SSHA} -s 패스워드입력
{SSHA}TuXt7LyRbmpzacWE4jjjdi8zUQNEcNYz

6. LDAP Admin 계정 생성 및 등록

cat <<EOF > chrootpw.ldif
dn: olcDatabase={0}config,cn=config
changetype: modify
replace: olcRootPW
olcRootPW: {SSHA}TuXt7LyRbmpzacWE4jjjdi8zUQNEcNYz
EOF
728x90
ldapmodify -Y EXTERNAL -H ldapi:/// -f chrootpw.ldif

--output--
SASL/EXTERNAL authentication started
SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
SASL SSF: 0
modifying entry "olcDatabase={0}config,cn=config"

7. LDAP 스키마(cosine.ldif, nis.ldif, inetorgperson.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

cp -av /usr/share/doc/samba-4.10.16/LDAP/samba.ldif /etc/openldap/schema/samba.ldif
ldapadd -Y EXTERNAL -H ldapi:/// -f /etc/openldap/schema/samba.ldif

8. Domain 수정 작업

cat <<EOF > chdomain.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=manager,dc=test,dc=com" read by * none

dn: olcDatabase={2}hdb,cn=config
changetype: modify
replace: olcSuffix
olcSuffix: dc=test,dc=com

dn: olcDatabase={2}hdb,cn=config
changetype: modify
replace: olcRootDN
olcRootDN: cn=manager,dc=test,dc=com

dn: olcDatabase={2}hdb,cn=config
changetype: modify
replace: olcRootPW
olcRootPW: {SSHA}TuXt7LyRbmpzacWE4jjjdi8zUQNEcNYz

dn: olcDatabase={2}hdb,cn=config
changetype: modify
replace: olcAccess
olcAccess: {0}to attrs=userPassword,shadowLastChange by
  dn="cn=manager,dc=test,dc=com" write by anonymous auth by self write by * none
olcAccess: {1}to dn.base="" by * read
olcAccess: {2}to * by dn="cn=manager,dc=test,dc=com" write by * read
EOF
ldapmodify -Y EXTERNAL -H ldapi:/// -f chdomain.ldif

--output--
SASL/EXTERNAL authentication started
SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
SASL SSF: 0
modifying entry "olcDatabase={1}monitor,cn=config"

modifying entry "olcDatabase={2}hdb,cn=config"

modifying entry "olcDatabase={2}hdb,cn=config"

modifying entry "olcDatabase={2}hdb,cn=config"

modifying entry "olcDatabase={2}hdb,cn=config"
cat <<EOF > basedomain.ldif
dn: dc=test,dc=com
o: test
dc: test
objectClass: top
objectClass: dcObject
objectclass: organization

dn: cn=manager,dc=test,dc=com
objectClass: organizationalRole
cn: manager
description: Directory Manager

dn: ou=People,dc=test,dc=com
objectClass: organizationalUnit
ou: People

dn: ou=Group,dc=test,dc=com
objectClass: organizationalUnit
ou: Group
EOF
ldapadd -x -D cn=manager,dc=test,dc=com -W -f basedomain.ldif

9. User 생성 작업

cat <<EOF > useradd.ldif
dn: uid=testuser,ou=People,dc=test,dc=com
objectClass: top
objectClass: account
objectClass: posixAccount
objectClass: shadowAccount
cn: testuser
uid: testuser
uidNumber: 1500
gidNumber: 1500
homeDirectory: /home/testuser
loginShell: /bin/bash
gecos: 
userPassword: {crypt}x
shadowLastChange: 17058
shadowMin: 0
shadowMax: 99999
shadowWarning: 7
EOF
ldapadd -x -D cn=manager,dc=test,dc=com -W -f useradd.ldif

10. SAMBA 세팅 (/etc/samba/smb.conf)

# See smb.conf.example for a more detailed config file or
# read the smb.conf manpage.
# Run 'testparm' to verify the config is correct after
# you modified it.

[global]
        workgroup = test.com
        security = user

        passdb backend = tdbsam
#       passdb backend = ldapsam:ldap://1.1.1.1
        ldap suffix = dc=test,dc=com
        ldap user suffix = ou=People
        ldap group suffix = ou=Group
        ldap delete dn = no
        ldap admin dn = cn=manager
        ldap ssl = no
        ldap passwd sync = yes
        printing = cups
        printcap name = cups
        load printers = yes
        cups options = raw

[homes]
        comment = Home Directories
        valid users = %S, %D%w%S
        browseable = No
        read only = No
        inherit acls = Yes

[printers]
        comment = All Printers
        path = /var/tmp
        printable = Yes
        create mask = 0600
        browseable = No

[print$]
        comment = Printer Drivers
        path = /var/lib/samba/drivers
        write list = @printadmin root
        force group = @printadmin
        create mask = 0664
        directory mask = 0775

11. slapd.conf 세팅

# 안에 도메인 수정
cp -av /usr/share/openldap-servers/slapd.ldif /etc/openldap/slapd.conf

12. 상태

pwd
/etc/openldap/slapd.d/cn=config

ls -ltr
total 20
-rw------- 1 ldap ldap 443 Jan 13 13:14 olcDatabase={-1}frontend.ldif
-rw------- 1 ldap ldap 378 Jan 13 13:14 cn=schema.ldif
-rw------- 1 ldap ldap 624 Jan 13 16:51 olcDatabase={0}config.ldif
drwxr-x--- 2 ldap ldap 132 Jan 13 17:44 cn=schema
-rw------- 1 ldap ldap 608 Jan 14 10:07 olcDatabase={1}monitor.ldif
-rw------- 1 ldap ldap 974 Jan 14 10:07 olcDatabase={2}hdb.ldif

13. LDAP Admin으로 관리

http://www.ldapadmin.org/download/ldapadmin.html

 


OpenLDAP 삭제

1. 서비스 중지

systemctl stop slapd

2. 패키지 삭제

yum remove openldap-servers
Removing:
 openldap-servers

3. DB 삭제

rm -rf /var/lib/ldap

4. 계정 삭제

userdel ldap

5. LDAP 재설치

systemctl stop slapd
systemctl stop nscd.service

rm -rf /var/lib/ldap
rm -rf /etc/openldap
rm -rf /run/openldap 
rm -rf /usr/lib64/openldap /usr/libexec/openldap

yum reinstall -y openldap openldap-servers openldap-clients
728x90
300x250

'IT > OpenLDAP' 카테고리의 다른 글

LDAP 사용자 자동 등록 처리  (0) 2022.02.15
OpenLDAP Logging 설정 방법  (0) 2022.02.03
LDAP Account Manager의 설정  (0) 2021.07.30
OpenLDAP memberOf overlay  (0) 2021.07.30
OpenLDAP ACL에 대한 설명  (0) 2021.07.30

+ Recent posts