Script to Convert Hostname to IP

Here is a shell script I wrote to translate NetBOIS names to IP addresses. SAMBA needs to be install for the nmblookup command. I work mostly on Linux / OS X but we are a Windows shop so I wrote this shell script to help convert hostnames to IP address for windows machines. Not every host is in WINS or DNS so this scripts combines the 2 queries.

Input file syntax:

Host1
Host2
Host3

Script:

#!/bin/bash
#
# Convert Windows NetBOIS Hostname to IP
# First tries WINS and if that fails it tries DNS
#
SEARCH_FILE=$1
 
TIME=`date +%s`
BASE=`echo $1 | cut -d. -f1`
GOOD="${BASE}_ip_${TIME}.txt"
BAD="${BASE}_noip_${TIME}.txt"
NO_PING="${BASE}_noping_${TIME}.txt"
WINS="1.1.1.1"
 
for i in $(cat $SEARCH_FILE); do
  IP=`nmblookup -U $WINS -R $i | grep \<00\> | sed -e 's/&lt;00&gt;//g' | cut -d\  -f1 | head -1`
  if [ $IP"M" == "M" ]; then
    IP=`nslookup $i | grep Address | grep -v \# | tail -1 | cut -d\  -f2`
    if [ $IP"M" == "M" ]; then
      LOGFILE=$GOOD
      IP=$i
    else
      LOGFILE=$NO_PING;
    fi
  else
    LOGFILE=$BAD;
  fi
  echo $IP >> $LOGFILE;
done

The script spits out a couple of file as defined by the GOOD and BAD variables.

GOOD file contains all the successfully lookups

BAD file contains all the failed lookups

If you find it handy let me know.

One Response to “Script to Convert Hostname to IP”

  1. Shawn Says:

    this script has everything dumping to one file, you need to modify the three “LOGFILE=$GOOD” at the bottom appropriately.

Leave a Reply

jump2top free wordpress themes