如何從 nmblookup 僅獲取 IP 位址以在 Bash 腳本中使用?

如何從 nmblookup 僅獲取 IP 位址以在 Bash 腳本中使用?

如果我做:

nmblookup myServerName

我得到:

192.168.6.106 myservername<00>

由於我想使用 Bash 腳本中返回的 IP nmblookup myServerName,因此我想知道僅返回 IP 而不是myservername<00>字串部分的最佳方法。我看過nmblookup 文檔,但我找不到對我有幫助的選項。

答案1

您可能需要添加一些更嚴格的檢查,包括健全性檢查,因為如果 myServerName 關閉,nmblookup 可能會失敗:

RES=$(nmblookup myServerName 2>/dev/null)
if test "$?" != "0"; then
  echo "nmblookup failed"
  # Do something
  exit 10
fi

IP1=$(echo "$RES" | sed 's/^\([0-9]*\)\..*/\1/')
IP1=$(printf '%d' "$IP1" 2>/dev/null)
test -z "$IP1" && IP1=256

IP2=$(echo "$RES" | sed "s/^$IP1\\.\\([0-9]*\\)\\..*/\\1/")
IP2=$(printf '%d' "$IP2" 2>/dev/null)
test -z "$IP2" && IP2=256

IP3=$(echo "$RES" | sed "s/^$IP1\\.$IP2\\.\\([0-9]*\\)\\..*/\\1/")
IP3=$(printf '%d' "$IP3" 2>/dev/null)
test -z "$IP3" && IP3=256

IP4=$(echo "$RES" | sed "s/^$IP1\\.$IP2\\.$IP3\\.\\([0-9]*\\).*/\\1/")
IP4=$(printf '%d' "$IP4" 2>/dev/null)
test -z "$IP4" && IP4=256

OK=1
test $IP1 -gt 255 && OK=0
test $IP2 -gt 255 && OK=0
test $IP3 -gt 255 && OK=0
test $IP4 -gt 255 && OK=0
if test "$OK" != "1"; then
  echo "nmblookup talking garbage"
  # Do something
  exit 11
fi

相關內容