代码之家  ›  专栏  ›  技术社区  ›  Karn Kumar

awk从nslookup输出获取IP和名称

awk
  •  0
  • Karn Kumar  · 技术社区  · 6 年前

    我有一个文件是 File1.txt 并保留一些IP地址。

    192.168.1.2
    192.168.1.3
    192.168.1.4
    

    通常当我们过去 nslookup 它通过DNS提供针对该IP的名称解析,如下所示。。

    # nslookup 192.168.1.2
    Server:         192.168.1.1
    Address:        192.168.1.1#53
    
    2.1.168.192.in-addr.arpa      name = rob.example.com.
    

    正如我们所看到的,上面的输出提供了许多信息,但是我只希望根据给定的IP捕获名称,因此使用awk获得所需的结果。

    下面是针对IP列表的for循环,它只是获取名称。

    cat File1.txt`;do nslookup $i | awk '/name/{print $4}';done
    
    rob.example.com
    tom.example.com
    tony.example.com
    

    是否有一个可能的一行程序,使他IP和名字都打印,就像没有写进脚本文件。

    192.168.1.2  rob.example.com
    192.168.1.3  tom.example.com
    192.168.1.4  tony.example.com
    

    尽管有猛击的解决方案。。

    #!/bin/bash
    
    iplist="File1.txt"
    
    while read -r ip; do
           printf "%s\t%s\n" "$ip" "$(dig +short -x $ip)"
       done < "$iplist"
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   RavinderSingh13 Nikita Bakshi    6 年前

    编辑: 如果OP的输入文件中有IPs,下面的内容可能会对您有所帮助。

    while read ip
    do
        nslookup "$ip" | awk -v ip="$ip" '/name/{print substr($NF,1,length($NF)-1),ip}'
    done < "Input_file"
    

    说明: 这只是为了解释,为了运行代码,请仅使用上面的代码。

    while read ip
        ##Starting a while loop which will read OP's Input_file which will have IPs in it. ip is the variable which has its value.
    do
        nslookup "$ip" | awk -v ip="$ip" '/name/{print substr($NF,1,length($NF)-1),ip}'  
        ##using nslookup and passing variable ip value to it, to get specific IPs server name and passing it to awk then.
        ##In awk command setting up a variable named ip whose value is shell variable ip value and then checking if a line is having name in it if yes then printing the last column value leaving last DOT. 
    done < "Input_file"
        ##Mentioning Input_file name here which should be passed.
    


    请尝试下列操作。(考虑到您的输入文件上有服务器名)

    while read ip
    do
       nslookup "$ip" |  awk '/Name:/{val=$NF;flag=1;next} /Address:/ && flag{print $NF,val;val=""}'
    done < "Input_file"
    
        2
  •  0
  •   Karn Kumar    6 年前

    啊!它非常简单,同时通过awk手册我得到了awk变量即直接。。

    $ for i in `cat File1.txt`;do nslookup $i | awk -v var=$i  '/name/{print var "\t", $4}';done
    
    192.168.1.2  rob.example.com
    192.168.1.3  tom.example.com
    192.168.1.4  tony.example.com