简体   繁体   中英

available hosts on a network

i am trying to write a bash script to determine the ip addresses and mac addresses of all hosts available on a network. for some reason, the Pingpacklist file keeps turning up empty. i know that entries in arp aren't permanent so thought i'd dump the arp after pinging half the network. but it still seems unable to get the arp entries for all addresses. any recommendations?

#! /bin/bash

tcpdump -i eth1 -n icmp >> Pingpacketlist &

count=0
mod=127;
for ip in 172.16.1.{1..254}; do
  let count=count+1;
  let res=$count%$mod;
  ping -c 1 -W 1 $ip > /dev/null 2> /dev/null;
  if [ $? -eq 0 ]; then    # for debugging
    echo "${ip} is up";
  else
    echo "${ip} is down";
  fi 
  if [ $res -eq 0 ]; then
    arp -n -i eth1 >> ARPResults 
  fi
done

Maybe use nmap instead?

nmap -sP  172.16.1.0/24

Lists all the hosts in the network, including MAC address.

If you want to record packets with tcpdump , I'd suggest using the -w option (which saves the binary representation of packets to a file), and then parse it afterards. Like this:

tcpdump -i eth1 -w Pingpacketlist icmp

And then read it back later like this:

tcpdump -r Pingpacketlist -n

But seriously, if I were trying to accomplish what you're doing, I would just use nmap . You can use nmap to discover the IP addresses and MAC addresses on your network like this:

nmap -oX nmap.xml -sP 172.16.1.0/24

You'll get as output a file ( nmap.xml ) with contents like this:

</host>
<host><status state="up" reason="arp-response"/>
<address addr="172.16.1.3" addrtype="ipv4"/>
<address addr="00:1A:70:A9:63:BE" addrtype="mac" vendor="Cisco-Linksys"/>
<hostnames>
</hostnames>
<times srtt="1804" rttvar="5000" to="100000"/>
</host>

You don't need to produce XML output if you don't want it; see Wesley answer for another nmap example.

If you really want to roll your own, consider looking at the arp table after every successful ping, like this:

for ip in 192.168.1.{1..254}; do
  ping -c 1 -W 1 $ip > /dev/null 2> /dev/null;
  if [ $? -eq 0 ]; then
    echo "${ip} is up";
    arp -n -i eth0 $ip | grep ether >> ARPResults
  else
    echo "${ip} is down";
  fi
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM