用于搜索 LDAP 条目的 Bash 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18204756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:14:10  来源:igfitidea点击:

Bash script to search for LDAP entries

bashopenldap

提问by rahuL

I have a bash script which is to be used to delete a particular user if it exists in a group.

我有一个 bash 脚本,用于删除组中存在的特定用户。

First I extracted all the group names and saved it to a file. As the next step, I thought I should parse through the file, and use the ldapsearch command on all the entries and grep the user, and if it exists, use ldapmodify to delete it.

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

My question is how to write the if condition, i.e if [ *ldapsearch query* == True];then

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

This is what my ldapsearch looks like, and the first line inside the while loop is to be the ifstatement.

这就是我的 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

On the CLI, this ldapsearch query returns the following output;

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

memberUid: testuser

memberUid: testuser

So essentially, if the ifstatement returns some value (i.e. the user exists), then I have to delete the user. How do I get a correct ifstatement to get a True or False result for the ldapsearch query?

所以本质上,如果if语句返回一些值(即用户存在),那么我必须删除用户。如何获得正确的if语句以获取 ldapsearch 查询的 True 或 False 结果?

采纳答案by fedorqui 'SO stop harming'

You can use the -zoption, that checks if the string is empty or not. [ -z "$string" ]is true if the string is empty. Then, this can make it:

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

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

For example say we want to check if a directory is empty:

例如,假设我们要检查目录是否为空:

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

All together:

全部一起:

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