This is the 8th day of my participation in the November Gwen Challenge. See the link for details: The last Gwen Challenge 2021

A script:

There is a network segment 192.168.3.0 in the company, now want to determine which hosts are online, which hosts are not online.

Shell script solution:

Method one:

Train of thought

First, loop the IP address of the target host. The IP address is divided into two parts:

STR =192.168.3. num= a natural number from 1 to 255, so num needs to be iterated and then concatenated with STR

IP=${str}${num}
Copy the code

#!/bin/Bash # define variable STR STR ="192.168.31."   
# forLoop through num #num is1-255The natural numbers of1.255.}
for num in {1.255.}
do
    ip=${str}${num}
    if ping -c1 -w1 ${ip} &>/dev/null; Then # If the ping can be pinged, the prompt IP online echo"$ip is online."
    elseIf the ping fails, the host is not online echo"$ip is offline"
    fi
done
Copy the code

The ping command has two parameters, one is -c and the other is -w

-c count specifies the number of echo signal requests to be sent (or received). The count variable indicates that the -w timeout option works only with the -c option. It causes the ping command to wait for a reply with the maximum timeout (after the last packet is sent)

Method 2:

Train of thought

Echo echo echo echo echo echo echo echo echo echo echo If? If? If? If the value is 0, the IP address can be pinged through. Otherwise, the IP address is offline.

#!/bin/bash
str="192.168.1."
for num in {1.255.}
do
    ip=${str}${num}
    ping -c1 -w1 ${ip} &>/dev/null# define NUM as $? If the command is executed successfully, $? =0NUM=$?if [ $NUM -eq 0]; then echo"$ip is online."
    else
         echo "$ip is offline"
    fi
done
Copy the code

Methods three

Train of thought

{1. In addition to 255}, you can also use seq 1 254

[root@laoxin-06 ~]# cat ping.sh 
#!/bin/bash
str="192.168.31."

# seq 1 254 
for num in `seq 1 254`    
do
	ip=${str}${num}
	ping -c1 -w1 ${ip} &>/dev/null 
        NUM=$?
        if [ $NUM -eq 0]; then echo"$ip is online" 
        else
		echo  "$ip is offline"
        fi

done

Copy the code

Script. 2:

When we go to interviews and are often asked about disk usage, we can write a script to determine the disk usage

#!/bin/Bash # intercept IP there are several ways to intercept IP=`ifconfig eth0 |awk -F " " 'NR==2{print $2}'`# define usage and convert it to the number SPACE=`df -Ph |awk '{print int($5)}'` 

for i in $SPACE
do# if the traversal value is greater than90, we consider the disk usage exceeded90%, and an alarm is generatedif [ $i -ge 90 ]
then
    echo "The disk usage of $IP has exceeded 90%. Please handle it promptly."

fi
done

Copy the code

Of course, there are many IP interception methods, here used a relatively simple one

conclusion

Shell scripts are not that difficult. Practice them in your daily learning.