1. Demand
find all unused IPs in a 192.168.0.* network segment
2. Realize
We know that finding methods that do not use IP can be done using the ping command. For a single IP judgment, use the following command
$Ping-C1 192.168.0.1PING192.168.0.1(192.168.0.1) About( -) bytes of data. -Bytes from192.168.0.1: icmp_seq=1Ttl= - Time=0.031Ms---192.168.0.1 PingStatistics---1Packets Transmitted,1Received0% packet loss, Time0msrtt min/avg/max/mdev =0.031/0.031/0.031/0.000Ms
If the message is similar, then the IP is determined to be connected and in use. If not, you can tell that it is not used. If you just look for an IP, you can try a few more to know, but this test efficiency is too low, unscientific, write a circular batch search under.
#!/bin/Bash forIinch$(seq 0 255); DoIP="192.168.0.${i}" Ping-C1${IP} &>/dev/NULL if[$?-ne0]; Thenprintf"${ip} can not reachable\n" fi Done
In this case, the bulk lookup of unused IP in the 192.168.0.* network segment is realized. But when executing the command you find that execution is very slow (there is no execution results, so you can perform your own experience). Obviously, this does not solve the problem of efficiency. At this point you must have thought that if you use multiple processes, you can solve this problem. Yes. Let's look at the following example.
#!/bin/Bashmax_thread_num= - forIinch$(seq 0 255); DoIP="192.168.0.${i}" ( Ping-C1${IP} &>/dev/NULL[$?-ne0] &&printf"${ip} can not reachable\n" )&num_ping=`PS-ef |grep "Ping"|grep-Vgrep|WC-l ' while["${num_ping}"-gt"${max_thread_num}"]; Do Sleep 1num_ping=`PS-ef |grep "Ping"|grep-Vgrep|WC-l ' Done Donewait
Perform discovery efficiency several times higher. The example above is to use & to place the process in the background and to control the number of processes by looping through the number of processes that the current ping command executes. Here Max_thread_num is set to 50, consider that ping consumes less resources can also be adjusted larger. If the command is consuming more resources, the max_thread_num should be smaller. Depending on server performance and command consumption of resources adjusted.
There is a way to use the file descriptor, read, we write down a look, the effect is the same, the example is as follows
#!/bin/Bashtemp_fifofile="/tmp/$$.fifo"Mkfifo${temp_fifofile}exec5<>${temp_fifofile}RM${temp_fifofile}max_thread_num= - for((i=0; i<${max_thread_num};i++)); Do Echo Done>&5 for((i=0; i<=255; i++)); DoRead-U5 (IP="10.135.17.${i}" Ping-C1${IP} &>/dev/NULL [ $? -ne0] && printf"${ip} can not reachable\n" Echo>&5 )& Donewaitexec5>&-Exit0
If it is another command that requires more process execution, you can modify it. Depending on the actual situation, choose one of these two methods to achieve. Method a relatively better understanding.
[Shell programming] Shell multithreaded operation instance