如何从挖掘结果中解析SRV记录的端口?

时间:2016-08-06 06:03:01

标签: bash dns port dig

我正在解析dig的输出,以获取SRV记录的端口。

export SERVER_DNS_NAME=myserver
echo "SERVER_DNS_NAME: " $SERVER_DNS_NAME
echo "dig: " $(dig +noall +answer $SERVER_DNS_NAME SRV )
echo "port old: " $(dig +noall +answer $SERVER_DNS_NAME SRV | cut -d ' ' -f 6)
SERVER_DIG_RESULT=$(dig +noall +answer $SERVER_DNS_NAME SRV )
echo "SERVER_DIG_RESULT: " $SERVER_DIG_RESULT
SERVER_STRING_ARRAY=($SERVER_DIG_RESULT)
for i in "${SERVER_STRING_ARRAY[@]}"
do
  :
  echo $i
done
SERVER_PORT=${SERVER_STRING_ARRAY[6]}
echo "server port new: " $SERVER_PORT
if [ -z $SERVER_PORT ]; then
  echo "invalid port"
  exit 1
fi
until nc -z $SERVER_DNS_NAME $SERVER_PORT
... do something

我的问题是有时端口位于数组项6,有时是7.

我的问题是:如何从挖掘结果中可靠地解析端口?

3 个答案:

答案 0 :(得分:3)

使用+short选项dig,这将为您提供最简化的输出,然后进行简单的解析:

% dig +short _xmpp-client._tcp.jabber.org. SRV
31 30 5222 hermes2v6.jabber.org.
30 30 5222 hermes2.jabber.org.

答案 1 :(得分:0)

您可能也喜欢这个:

host -t SRV mySRVdomain.local                                           
# mySRVdomain.local has SRV record 1 1 2368 e04dc24b-96c6-4b52-8356-42be0d34e7bb.mySRVdomain.local.


# get it as host:port
host -t SRV mySRVdomain.local | sed -r 's/.+ ([^ ]+) ([^ ]+)\.$/\2:\1/g'

# This will print: e04dc24b-96c6-4b52-8356-42be0d34e7bb.mySRVdomain.local:2368
# which is the first real URL with PORT

它可能与您所需的不完全相同,但是您可以理解它

答案 2 :(得分:0)

使用 Curl 和 AWK 形成快速命令:

curl http://$(dig +short {HOST} srv | awk '{printf "%s:%s\n",$4,$3}')