Dns

為什麼 host 和 nslookup 認為 IP 地址是主機名?

  • September 8, 2020

為什麼這個命令會失敗(這是實際命令的簡化版本)?

/tmp $ echo 74.6.231.20 | xargs -n1 -I {} echo "$(host -d {})"
Trying "74.6.231.20.<REDACTED>.<REDACTED>.com"
Trying "74.6.231.20"
Host 74.6.231.20 not found: 3(NXDOMAIN)
Received 95 bytes from 10.163.24.1#53 in 1 ms

host命令將74.6.231.20 視為主機名而不是 IP 地址,這就是它失敗的原因(即沒有 74.6.231.20 主機名/FQDN)。

直接指定 IP 地址有效:

/tmp $ echo 216.58.195.78 |  xargs -n1 -I {} echo "$(host -d 216.58.195.78)"
Trying "78.195.58.216.in-addr.arpa"
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 21425
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;78.195.58.216.in-addr.arpa.    IN  PTR

;; ANSWER SECTION:
78.195.58.216.in-addr.arpa. 85730 IN    PTR sfo07s16-in-f78.1e100.net.
78.195.58.216.in-addr.arpa. 85730 IN    PTR sfo07s16-in-f14.1e100.net.

Received 113 bytes from 10.163.24.1#53 in 2 ms

消除echo命令也可以:

/tmp echo 74.6.231.20 | xargs -n1 -I {} sh -c  "(host {})"
20.231.6.74.in-addr.arpa domain name pointer media-router-fp73.prod.media.vip.ne1.yahoo.com.

問題似乎是 xargs 與 echo 的組合以及 xargs 如何進行 {} 字元串替換。

ps 我知道有變通方法,我主要感興趣的是找到阻止此命令成功執行的已損壞互動。謝謝。

發生這種情況是因為您的 shell 在將命令行參數作為參數傳遞給命令之前對它們執行變數和命令替換,因此$(host -d {})xargs. 第二個echo命令實際上輸出了這個:

Trying "{}.<REDACTED>.<REDACTED>.com"
Trying "{}"
Host {} not found: 3(NXDOMAIN)
Received 95 bytes from 10.163.24.1#53 in 1 ms

然後在輸出中xargs替換{}為 IP 地址,使其看起來像host命令出現故障。set -x您可以在執行管道之前通過使用自己查看它:

( set -x; echo 74.6.231.20 | xargs -n1 -I {} echo "$(host -d {})" )

+ echo 74.6.231.20
++ host -d '{}'
+ xargs -n1 -I '{}' echo 'Trying "{}.<REDACTED>.<REDACTED>.com"
Trying "{}"
Host {} not found: 3(NXDOMAIN)
Received 95 bytes from 10.163.24.1#53 in 1 ms'
Trying "74.6.231.20.<REDACTED>.<REDACTED>.com"
Trying "74.6.231.20"
Host 74.6.231.20 not found: 3(NXDOMAIN)
Received 95 bytes from 10.163.24.1#53 in 1 ms

在這個特定範例中,如果您只想顯示 的輸出host,則無需先擷取它然後再顯式地擷取echo它。這樣做就足夠了:

echo 74.6.231.20 | xargs -n1 host -d

編輯:

這是一個如何將xargs輸入傳遞給多個命令的範例。這是有效的,因為bash將在-c命令之後將任何參數分配為位置參數,以$0.

echo 74.6.231.20 | xargs -n1 -I '{}' /bin/bash -c 'echo "$0"; host -d "$0"' '{}'

引用自:https://unix.stackexchange.com/questions/607884