0

我正在尝试理解 Linux Bash 脚本。该脚本的目的是仅对某些 dyndns 用户(通过使用 ufw 规则)限制对服务器服务的访问。部分脚本:

ALLOWEDUSERS="client1.dyndns.org client2.dyndns.org"

for host in $ALLOWEDUSERS ; do
    ip=`host $host | cut -d ' ' -f 4`
    if [ $? -eq 0 ]; then
       ufw allow proto tcp from $ip to any
    fi
done

好的

for host in $ALLOWEDUSERS ; do

很清楚,它循环通过 ALLOWEDUSERS,

据我所理解

if [ $? -eq 0 ]; then

检查之前执行的命令是否为真(如果是则添加 ufw 规则)

但是片段的其余部分如何

ip=`host $host | cut -d ' ' -f 4`

检查客户端 IP 是否来自允许的 dyndns 帐户?

非常感谢你的帮助,

托尼

4

2 回答 2

1

它并没有真正检查任何东西。

的输出host $host类似于 $host has address xxx.xxx.xxx.xxx.

例如:

$ host localhost
localhost has address 127.0.0.1

然后cut -d ' ' -f 4隔离第四部分,即IP地址。这用作ufw命令的 IP 地址。

于 2013-11-11T21:51:53.520 回答
0

该脚本本质上等同于:

ALLOWEDUSERS="client1.dyndns.org client2.dyndns.org"

for host in $ALLOWEDUSERS ; do
    ip=`host $host | cut -d ' ' -f 4`
    ufw allow proto tcp from $ip to any
done

原始if脚本中的 是检查cut, not的结果host,而且它总是成功的,所以它没有任何用处。

当 DynDNS 主机名有效时,将向防火墙添加一条规则以允许它。

当找不到主机名时,host命令会打印:

Host clientN.dyndns.org not found: 3(NXDOMAIN)

$ip也会如此found:。这将尝试这样做:

ufw allow proto tcp from found: to any

由于这不是有效的防火墙规则,我希望它会被忽略并发出错误消息。

如果你想做脚本显然试图做的事情,它应该是:

ALLOWEDUSERS="client1.dyndns.org client2.dyndns.org"

for host in $ALLOWEDUSERS ; do
    hostresult=`host $host`
    if [ $? -eq 0 ]; then
        ip=`echo "$hostresult" | cut -d ' ' -f 4`
        ufw allow proto tcp from $ip to any
    fi
done
于 2013-11-11T22:05:38.560 回答