用于检查 LDAP 上的 LDAP 条目数的脚本.客户端计算机上的 CONF 并更新缺少的客户端计算机



>我正在尝试在脚本中使用 sed 命令来搜索以 HOST 开头的行,然后检查主机名的匹配模式并在 LDAP 配置文件中添加缺少的。

LDAP 中的示例条目。会议

HOST nzlsfn55.zeus.ghsewn.com nzlsfn60.zeus.ghsewn.com  nznsfn60.zeus.ghsewn.com

现在我如何搜索模式并使用 sed 添加缺少的条目,任何帮助将不胜感激。

如果您有主机列表并希望添加缺少的主机:

#!/bin/bash
for arg; do
    grep &>/dev/null "^HOST +.*<$arg>" ||
        sed -i "s/$/ $arg/" /etc/ldap/ldap.conf
done

像这样使用脚本:

./script host1 host2 host3

在测试之前备份/etc/ldap/ldap.conf。(未在那里测试)

编辑

若要满足新要求,请参阅以下代码:

#!/bin/bash
hosts="host1 host2 host3"
for arg in $hosts; do
    grep &>/dev/null "^HOST +.*<$arg>" ||
        sed -i "s/$/ $arg/" /etc/ldap/ldap.conf
done

我会为此使用GNU awk。假设您在一个名为 hosts.txt 的文件中有一个主机列表(行分隔),您可以运行以下命令:

awk -f script.awk hosts.txt /etc/ldap/ldap.conf > new_ldap.conf

script.awk内容:

FNR==NR {
    hosts[$0]++
    next
}
/^HOST/ {
    for (j=2; j<=NF; j++) {
        array[$j]++
    }
    for (i in hosts) {
        if (!(i in array)) {
            $0 = $0 OFS i
        }
    }
    delete array
}1

我使用下面的代码来完成我的任务,我相信我的代码段必须有更简单的方法或改进 - 谢谢大家的输入

如果 [ -e/etc/openldap/ldap.conf ]; 然后

        entries=`grep -i host /etc/openldap/ldap.conf`
        count=`grep -i host /etc/openldap/ldap.conf | wc -w`

else
        echo " no ldap.conf file available "
        exit
fi
#if condition checking for no host entry
if [ $count -eq 0 ];
then

        echo " no host entry available in config file "
        exit
fi

#if condition checking for less than 3 ldap entries
if [ $count -eq 4 ];
then
        echo " `hostname` has the following ldap entries : $entries "
else
        #less then than 3 entries will get updated here
        if [ $count -lt 4 ];
        then
        sed -i.bak 's/^host.*|^HOST.*/host nzlsfn55.zeus.ghsewn.com nzlsfn60.zeus.ghsewn.com  nznsfn60.zeus.ghsewn.com/' /etc/openldap/ldap.conf
        echo " Sucessfully added LDAP hosts"
        fi

最新更新