用于搜索LDAP条目的Bash脚本

时间:2013-08-13 08:57:43

标签: bash openldap

我有一个bash脚本,用于删除特定用户(如果它存在于组中)。

首先,我提取了所有组名并将其保存到文件中。下一步,我认为我应该解析文件,并在所有条目上使用ldapsearch命令并grep用户,如果存在,请使用ldapmodify删除它。

我的问题是如何编写if条件,即if [ *ldapsearch query* == True];then

这是我的ldapsearch的样子,而while循环中的第一行是if语句。

while read grp;do
        ldapsearch -w 'ldappass' -D "cn=adminuser,dc=some-domain,dc=com"  -b "cn=$grp,ou=group,dc=some-domain,dc=com"  | grep $someuser
done</home/someuser/tempfile.txt

在CLI上,此ldapsearch查询返回以下输出;

memberUid: testuser

基本上,如果if语句返回某个值(即用户存在),那么我必须删除该用户。如何获取正确的if语句以获取ldapsearch查询的真或假结果?

1 个答案:

答案 0 :(得分:3)

您可以使用-z选项检查字符串是否为空。如果字符串为空,则[ -z "$string" ]为true。然后,这可以做到:

if [ ! -z "$(yourcommand)" ]; then
    do_things
fi

例如,我们要检查一个目录是否为空:

if [ ! -z "$(ls)" ]; then
   echo "there is something"
else
   echo "this dir is empty"
fi

所有在一起:

while IFS= read -r grp;do
   if [ ! -z "$(ldapsearch -w 'ldappass' -D "cn=adminuser,dc=some-domain,dc=com"  -b "cn=$grp,ou=group,dc=some-domain,dc=com" | grep $someuser)" ]; then
      remove $someuser
   fi
done < /home/someuser/tempfile.txt