Shell script programming (thirteen)

Demand assumption problem solving

I put forward a requirement assumption in the blog Shell Script Programming (1):

Test how many hosts in the current subnet of the company can be connected (ping), and record the ip address of the ping PC.

 

After the study of the previous twelve blogs, everyone should have a certain grasp of the variables, operators, control statements and functions of the Shell programming language, then we should have the ability to solve this problem.

 

Problem solving process:

1. Check the IP address of your computer: ifconfig

My computer IP is 192.168.1.132, because all our company's PCs are connected to the same router, so our company's PCs are in the network segment 192.168.1.1 to 192.168.1.254, so my PC needs to check to be able to ping this Which computers are within the network segment.

2. After the above analysis, if you write a shell script, you need to define a variable in the script program to represent an IP address between the network segment 192.168.1.1 to 192.168.1.254, and because this is a circular search, you need to use Loop statement for or while. When pinging, you need to see the results, so you need to use $?. Because you need to record the ip address of the ping PC, you need to create a file to store the results.

 

The sample program is as follows:

#!/bin/bash

I=0

touch result.txt

while [ $I -lt 255 ]

do

       I=`expr$I + 1`

       echo"ping host: 192.168.1.$I"

       ping-c 1 192.168.1.$I

       if[ $? -eq 0 ]

       then

              echo"host:192.168.1.$I can be connected"

              echo"192.168.1.$I" >> result.txt

       else

              echo"host:192.168.1.$I can't be connected"

       be

done

 Note: If your company has more than one network segment, you can add a loop statement in the program.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325390290&siteId=291194637