Shell script efficiently detects host survival

Requirements:
A small A of an operation and maintenance company wants to re-plan the IP address. He wants to detect the unused ip in the 192.168.1.0 network segment for planning allocation, then if the ip has been allocated, it will not be used.

Implementation process: shell script implementation

Create a test.sh script in any directory of the server. The content of the script is as follows
#!/bin/bash #Test the
surviving host
test()
{
for i in $(seq 1 20)
do
ping -c 2 192.168.1.$i> / dev/null
if [$? -eq 0 ]; then
echo "192.168.1.$i, survived"
else
echo "192.168.1.$i, failed"
fi
done
}

test

Note: In the process of testing the script, we can sample and test several hosts, and then change the 20 in the loop to 254 after confirming that the script is successful. If you are not sure about the script in the early stage, you should not loop all the hosts at once.

In the above script content,
Ping -c 2 represents. If no data is returned by pinging an iP twice, it means that the ip is not assigned

Experimental verification
Shell script efficiently detects host survival

Conclusion: It takes about 1s to ping a successful host, and 2s to a failed host.
If all hosts in this network segment fail, it takes 254*2=408s to complete all the iP checks, which is very slow

Optimize script: (multithreaded)

Change the script content to the following
Shell script efficiently detects host survival

#!/bin/bash
for i in {1..20}
do
{
ping -c 2 192.168.1.$i >/dev/null
if [ $? = 0 ];then
echo "192.168.1.$i 存活"
else
echo "192.168.1.$i 不存活"
fi
} &
done
wait

& Is to put the process in the background without waiting, wait is to wait for all processes to execute before launching. If there is no wait, the program cannot be exited because the parent process exits first, and the child process has not finished execution. This situation is the so-called zombie process.

Note: The results displayed by multi-threading are consistent with the script of the implementation process, but the multi-threaded script does not need to wait, so the results displayed are not displayed in the order of ip

Result verification
before script optimization:
Shell script efficiently detects host survival

After script optimization
Shell script efficiently detects host survival

Execution efficiency is 8 times faster

The result of each execution of multi-threading, ip sorting is not consistent
Shell script efficiently detects host survival

Guess you like

Origin blog.51cto.com/14483703/2595308