How can I write a Linux bash script that tells me which computers are ON in my LAN?

前端 未结 16 1560
攒了一身酷
攒了一身酷 2020-12-12 11:59

How can I write a Linux Bash script that tells me which computers are ON in my LAN?

It would help if I could give it a range of IP addresses as input.

16条回答
  •  一向
    一向 (楼主)
    2020-12-12 13:02

    Some machines don't answer pings (e.g. firewalls).

    If you only want the local network you can use this command:

    (for n in $(seq 1 254);do sudo arping -c1 10.0.0.$n &  done ; wait) | grep reply | grep --color -E '([0-9]+\.){3}[0-9]+'
    

    Explanations part !

    1. arping is a command that sends ARP requests. It is present on most of linux.

    Example:

    sudo arping -c1 10.0.0.14
    

    the sudo is not necessary if you are root ofc.

    • 10.0.0.14 : the ip you want to test
    • -c1 : send only one request.

    1. &: the 'I-don't-want-to-wait' character

    This is a really useful character that give you the possibility to launch a command in a sub-process without waiting him to finish (like a thread)


    1. the for loop is here to arping all 255 ip addresses. It uses the seq command to list all numbers.

    1. wait: after we launched our requests we want to see if there are some replies. To do so we just put wait after the loop. wait looks like the function join() in other languages.

    1. (): parenthesis are here to interpret all outputs as text so we can give it to grep

    1. grep: we only want to see replies. the second grep is just here to highlight IPs.

    hth

    Edit 20150417: Maxi Update !

    The bad part of my solution is that it print all results at the end. It is because grep have a big enough buffer to put some lines inside. the solution is to add --line-buffered to the first grep. like so:

    (for n in $(seq 1 254);do sudo arping -c1 10.0.0.$n &  done ; wait) | grep --line-buffered reply | grep --color -E '([0-9]+\.){3}[0-9]+'
    

提交回复
热议问题