Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use shell to detect IP usage of Network Segment

Shulou Source: shulou.com Published: 2022-06-03 07:41:45 11月15日 Update

Editor to share with you how to use shell to detect the use of IP in network segments. I hope you will get something after reading this article. Let's discuss it together.

The code is as follows:

#! / bin/bash

# main

Network=192.168.1

Ping_count=3

IP=1

: > IP_use

: > IP_idle

: > ping_action

Echo "`date" +% Y%m%d% H:%M:%S "`- > script starts execution."

While [$IP-lt 255]

Do

Host=$network.$IP

Echo "- > starts to check whether the communication of $host server is normal, and the number of ping times is $ping_count."

Ping $host-c $ping_count > .ping_tmp

Sleep 1

Cat .ping _ tmp > > ping_action

Echo "- > Server $host detection completed."

Sum_ping= `tail-2.ping _ tmp | head-1 | awk-F,'{print$2}'| cut-c 2-2`

Loss_ping= `tail-2.ping _ tmp | head-1 | awk-F,'{print$4}'| cut-c 2-5`

If [$sum_ping-eq $ping_count]; then

Echo "--> $host IP is already in use"

Echo "--> $host IP is already in use" > > IP_use

Else

Echo "$host IP is currently free: $loss_ping"

Echo "$host IP is currently free" > > IP_idle

Fi

IP=$ ((IP+1))

Done

The echo "`date" +% Y%m%d% H:%M:%S "`- > script has finished running."

To implement all the IP of a network segment of Ping and check whether the network connection status is normal, there are many methods that can be implemented. Here are two methods, as follows:

Script 1

The code is as follows:

#! / bin/sh

# all IP of Ping IP address range

# 2012-02-05

Ip=1 # by modifying the initial value

While [$ip! = "254]; do

# yes is normal, no host does not exist or is not normal

Ping 192.168.0.$ip-c 2 | grep-Q "ttl=" & & echo "192.168.0.$ip yes" | | echo "192.168.0.$ip no"

Ip= `expr "$ip"+"1" `

Done

Output result:

192.168.0.1 yes

192.168.0.2 no

192.168.0.3 no

192.168.0.4 no

192.168.0.5 yes

192.168.0.6 no

192.168.0.7 yes

...

Script 2

The code is as follows:

#! / bin/sh

# all IP of Ping IP address range

# 2012-02-05

Ip= "192.168.0."

For i in `seq 1 254`

Do

Ping-c 2$ ip$i | grep-Q 'ttl=' & & echo "$ip$i yes" | | echo "$ip$i no"

# yes is normal, no host does not exist or is not normal

Done

Output result:

192.168.0.1 yes

192.168.0.2 no

192.168.0.3 no

192.168.0.4 no

192.168.0.5 yes

192.168.0.6 no

192.168.0.7 yes

...

After reading this article, I believe you have a certain understanding of "how to use shell to detect the use of IP in network segments". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

Tags: Network segment detection script code situation host server idle article result service output initial value dead method more times status knowledge network Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn macOS NVidia Docker MySQL