for循环语句

 

 

 

 

一shell脚本for循环语句

 

 

(一)for循环语句介绍

 

循环执行:将某代码段重复运行多次,重复运行多少次。也就是循环次数事先已知或者循环次数事先未知,有进入条件和退出条件。


循环语句有for, while, until

 

 

 

查看帮助文档,有两种语法

因为NAME是变量名,不加$

[root@centos7 ~]# type  for
for is a shell keyword
[root@centos7 ~]# help for
for: for NAME变量名 [in WORDS ... ] ; do COMMANDS; done

0420变量值就是列表中的某个值。有几个单词就会执行几遍
Execute commands for each member in a list. The `for' loop executes a sequence of commands for each member in a list of items. If `in WORDS ...;' is not present, then `in "$@"' is assumed. For each element in WORDS, NAME is set to that element, and the COMMANDS are executed. Exit Status: Returns the status of the last command executed. for ((: for (( exp1; exp2; exp3 )); do COMMANDS; done Arithmetic for loop. Equivalent to (( EXP1 )) while (( EXP2 )); do COMMANDS (( EXP3 )) done EXP1, EXP2, and EXP3 are arithmetic expressions. If any expression is omitted, it behaves as if it evaluates to 1. Exit Status: Returns the status of the last command executed.

 

 

 

 

 

 

对比case,如果name是变量名,要加$

[root@centos7 ~]# help  case
case: case WORD in [PATTERN [| PATTERN]...) COMMANDS ;;]... esac Execute commands based on pattern matching. Selectively execute COMMANDS based upon WORD matching PATTERN. The `|' is used to separate multiple patterns.  Exit Status: Returns the status of the last command executed.

 

 

 

 

 

 

 

(1)第1种语法——变量取值型

 

for 变量名 in 列表;do


循环体


done

 


执行机制:依次将列表中的元素赋值给“变量名”; 每次赋值后即执行一次循环体; 直到列表中的元素耗尽,循环结束。

 

在此结构中"in变量取值列表”可以省略,省略时相当于in "$@"
也就是使用for i就相当于使用for i in "$@"
在这种for循环语句语法中, for关键字后面会有一个“变量名”,
变量名依次获取in关键字后面的变量取值列表内容(以空格分隔),
每次仅取一个,然后进入循环(do和done之间的部分)
执行循环内的所有指令,当执行到done时结束本次循环。
之后, “变量名”再继续获取变量列表里的下一个变量值,继续执行循环内的所有指令,
当执行到done时结束返回,以此类推,直到取完变量列表里的最后一个值并进入循环执行到done结束为止。
 
 
 
 
 
 
for循环执行流程图
 
 

 

 

 

 

 

 

 

 

 

 

(2)第2种语法——C语言for循环语句

 

 

第二种for循环语句称为C语言型for循环语句,其语法结构如下:
 
for ( (exp1; exp2; exp3))
do
指令...
done
 

 

for关键字后的双括号内是三个表达式,第一个是变量初始化(例如: i=0),
 
第二个为变量的范围(例如: i<100 ),第三个为变量自增或自减(例如: i++)。
 
当第一个表达式的初始化值符合第二个变量的范围时,就进入循环执行;当条件不满足时就退出循环。
 

 

 

 

 

 

(二)列表生成方式

 

 

 

(1)直接给出列表元素

[root@centos73 shell_scripts]# vim  for.sh
[root@centos73 shell_scripts]# bash  for.sh num is 1 num is 2 num is 3 num is 4 [root@centos73 shell_scripts]# cat for.sh #!/bin/bash #Author:wang for num in 1 2 3 4 #写完4个数就会执行4次循环 do echo "num is $num" done

 

 

 

 

 

 

 


(2)整数列表

 
 {start..end},{start..end..step}

 

利用大括号{ }生成数字序列

[root@centos73 shell_scripts]# vim  for1.sh 
[root@centos73 shell_scripts]# bash  for1.sh 
num  is  1 num is 2 num is 3 num is 4 [root@centos73 shell_scripts]# cat for1.sh #!/bin/bash #Author:wang for num in {1..4} #写完4个数就会执行4次循环 do echo "num is $num" done

 

 

 

 

 

[root@centos73 shell_scripts]# cat  for1.sh 
#!/bin/bash
#Author:wang
for   num  in {a..g} do echo "num is $num" done [root@centos73 shell_scripts]# bash for1.sh num is a num is b num is c num is d num is e num is f num is g

 

 

 

 

 

 

{start..end..step}

[root@centos73 shell_scripts]# cat  for1.sh 
#!/bin/bash
#Author:wang
for   num  in  {10..2..1}从10到2递减,步长是1 do echo "num is $num" done [root@centos73 shell_scripts]# vim for1.sh [root@centos73 shell_scripts]# bash for1.sh num is 10 num is 9 num is 8 num is 7 num is 6 num is 5 num is 4 num is 3 num is 2

 

 

 

 

 

 

 

(3)使用seq生成数字序列

 

$(seq [start [step]] end)

[root@centos73 shell_scripts]# bash   for_seq.sh
1
3
5
7
9 11 13 15 17 [root@centos73 shell_scripts]# cat for_seq.sh #!/bin/bash #Author=wang for i in `seq 1 2 18` do echo $i done [root@centos73 shell_scripts]# 

 

 

 

 

 

 

 

注意如果是倒序,那么步长前面要加上-

[root@centos73 shell_scripts]# bash  for_seq_1.sh
10
8
6
4
2 0 [root@centos73 shell_scripts]# cat for_seq_1.sh #!/bin/bash #Author=wang for i in `seq 10 -2 0` do echo $i done

 

 

 

 

 

 

[root@centos73 shell_scripts]# seq  1  5  66
1
6 11 16 21 26 31 36 41 46 51 56 61 66

 

 

 

 

 

 

 

注意如果是倒序显示步长要加负号

[root@centos73 shell_scripts]# seq   66   5  1
[root@centos73 shell_scripts]# seq 66 -5 1 66 61 56 51 46 41 36 31 26 21 16 11 6 1

 

 

 

 

 

 

[root@centos73 shell_scripts]#
bash for_3sum.sh 3367 [root@centos73 shell_scripts]# cat for_3sum.sh #!/bin/bash #Author:wang sum=0 for i in `seq 1 100`;do if [ $[i%3] -ne 0 ]; then let sum+=i fi done echo $sum [root@centos73 shell_scripts]# vim for_3sum.sh [root@centos73 shell_scripts]# bash for_3sum.sh 3367 [root@centos73 shell_scripts]# cat for_3sum.sh #!/bin/bash #Author:wang sum=0 for i in `seq 1 100`;do if [ "$[i%3]" -ne 0 ]; then let sum+=i fi done echo $sum

 

 

 

 

 

 

 

 

(4)返回列表的命令$(COMMAND)

 

注意要加上反引号

[root@centos73 shell_scripts]# cat   for_command.sh
#!/bin/bash
#Author=wang
for i in `ls /etc`;do echo $i done

 

 

 

 

 

 

[root@centos73 shell_scripts]# bash  for_command.sh   | wc
    188     188    1803 [root@centos73 shell_scripts]# bash for_command.sh | head adjtime aliases aliases.db alternatives anacrontab asound.conf at.deny audisp audit bash_completion.d [root@centos73 shell_scripts]# bash for_command.sh | tail vmware-tools vsftpd wpa_supplicant X11 xdg xinetd.d yum yum.conf yum.repos_bak yum.repos.d

 

 

 

 

 

 

[root@centos73 shell_scripts]# bash  command1.sh 
filename is /root/shell_scripts/1.sh
filename is /root/shell_scripts/2.sh filename is /root/shell_scripts/backup1.sh filename is /root/shell_scripts/backup.sh filename is /root/shell_scripts/case1.sh filename is /root/shell_scripts/case.sh filename is /root/shell_scripts/command1.sh filename is /root/shell_scripts/for1.sh filename is /root/shell_scripts/for_3sum.sh filename is /root/shell_scripts/for.sh filename is /root/shell_scripts/for_sum.sh [root@centos73 shell_scripts]# cat command1.sh #!/bin/bash #Author:wang for filename in `ls /root/shell_scripts/*.sh`;do echo filename is $filename done

 

 

 

 

[root@centos73 shell_scripts]# bash  command1.sh 
filename is /root
filename is /root/shell_scripts/1.sh filename is /root/shell_scripts/2.sh filename is /root/shell_scripts/backup1.sh filename is /root/shell_scripts/backup.sh filename is /root/shell_scripts/case1.sh filename is /root/shell_scripts/case.sh filename is /root/shell_scripts/command1.sh filename is /root/shell_scripts/for1.sh filename is /root/shell_scripts/for_3sum.sh filename is /root/shell_scripts/for.sh filename is /root/shell_scripts/for_sum.sh [root@centos73 shell_scripts]# cat command1.sh #!/bin/bash #Author:wang for filename in ~ /root/shell_scripts/*.sh;do echo filename is $filename done

 

 

 

 

 

 

 

 

(5)使用使用通配符glob生成列表,如:*.sh

 

[root@centos73 shell_scripts]# bash  command1.sh 
filename is /root
filename is /root/shell_scripts/1.sh filename is /root/shell_scripts/2.sh filename is /root/shell_scripts/backup1.sh filename is /root/shell_scripts/backup.sh filename is /root/shell_scripts/case1.sh filename is /root/shell_scripts/case.sh filename is /root/shell_scripts/command1.sh filename is /root/shell_scripts/for1.sh filename is /root/shell_scripts/for_3sum.sh filename is /root/shell_scripts/for.sh filename is /root/shell_scripts/for_sum.sh [root@centos73 shell_scripts]# cat command1.sh #!/bin/bash #Author:wang for filename in ~ /root/shell_scripts/*.sh;do echo filename is $filename done

 

 

 

 



[root@centos73 shell_scripts]# bash  command1.sh 
filename is /root/shell_scripts/1.sh
filename is /root/shell_scripts/2.sh filename is /root/shell_scripts/backup1.sh filename is /root/shell_scripts/backup.sh filename is /root/shell_scripts/case1.sh filename is /root/shell_scripts/case.sh filename is /root/shell_scripts/command1.sh filename is /root/shell_scripts/for1.sh filename is /root/shell_scripts/for_3sum.sh filename is /root/shell_scripts/for.sh filename is /root/shell_scripts/for_sum.sh [root@centos73 shell_scripts]# cat command1.sh #!/bin/bash #Author:wang for filename in `ls /root/shell_scripts/*.sh`;do echo filename is $filename done

 

 

 

 

[root@centos73 shell_scripts]# cat   for_*sh.sh
#!/bin/bash
#Author=wang for i in "*.sh";do echo this is $i done

 

 

 

 

[root@centos73 shell_scripts]# bash   for_*sh.sh
this is 100sum_100.sh 19_1.1.sh 19_1.sh 19_2.sh 1.sh 2.sh 33.sh 34.sh 5.sh argsnum1.sh argsnum.sh array.sh a.sh backup.sh break.sh case_1.sh case1.sh case.sh checkdisk.sh checkint.sh color_black.sh color_brown.sh color_green.sh color_rad.sh color.sh color_yellow.sh command1.sh continue.sh copy_cmd.sh crack_passwords.sh create_user1.sh createuser_1.sh createuser2.sh create_user.sh createuser.sh dadengyao.sh dengyao.sh diskcheck.sh equicrural_triangle.sh excute.sh factorial.sh file_KS.sh filetype.sh for1.sh for_3sum.sh for_command.sh for_seq_1.sh for_seq.sh for.sh for_*sh.sh for_sum.sh func1.sh func2.sh func3.sh gecos.sh guess_digit_endlessloop1.sh guess_digit_endlessloop.sh guess_digit.sh host_online.sh isoscelestriangle_2.sh isoscelestriangle.sh killcrackers.sh killcrackers_while.sh login.sh log.sh matrix.sh monitor_connections1.sh monitor_connections.sh nine_nine_multiplication_table.sh nine*nine_multiplication_table.sh nologin.sh randhtml_sedway.sh randhtml.sh randhtml_trmethod.sh rand_max_min1.sh rand_max_min.sh random_for.sh random_while.sh rectangle.sh scan_ip1.sh scan_ip_for.sh scan_ip.sh scan_ip_while.sh score.sh select_quit1.sh select_quit.sh sum_100_1.sh sum_100.sh sum.sh trap_9signal.sh trap.sh triangle1.sh triangle.sh triangle_tree.sh use_exp.sh user_passwd.sh while_read_users.sh yesorno_case.sh yesorno_if.sh yesorno.sh

 

 

 

 

 

 

 

 

(6)变量引用:$@, $*

 

[root@centos73 shell_scripts]# cat  for2.sh
#!/bin/bash
#Author=wang
for i in `ls $@`;do echo $i done

 

 

 

[root@centos73 shell_scripts]# bash for2.sh | wc
    117     118    1589 [root@centos73 shell_scripts]# bash for2.sh | head 100sum_100.sh 19_1.1.sh 19_1.sh 19_2.sh 1.sh 2.sh 33.sh 34.sh 5.sh argsnum1.sh [root@centos73 shell_scripts]# bash for2.sh | tail trap.sh triangle1.sh triangle.sh triangle_tree.sh use_exp.sh user_passwd.sh while_read_users.sh yesorno_case.sh yesorno_if.sh yesorno.sh

 

 

 

 

 

 

 

 

 

二for循环示例

 

(一)求和1-100的偶数

 

 

完整脚本

[root@centos73 shell_scripts]# cat  for_sum.sh 
#!/bin/bash
#Author:wang

sum=0 for i in {2..100..2} do let sum+=i done echo $sum

 

 

 

 

 

执行结果

[root@centos73 shell_scripts]# bash  for_sum.sh 
2550

 

 

 

 

脚本解析

sum=0 对变量进行定义,初始值为0

let sum+=i 表示变量进行自增,相当于sum=sum+i

 

 

 

 

 

 下面是更容易理解的写法

[root@centos73 shell_scripts]# cat  for_sum.sh 
#!/bin/bash
#Author:wang

sum=0 for i in {2..100..2} do let sum=sum+i done echo $sum [root@centos73 shell_scripts]# bash for_sum.sh 2550

 

 

 

 

 

 因为是一个整体,要使用中括号

[root@centos73 shell_scripts]# bash  for_sum.sh 
2550
[root@centos73 shell_scripts]# cat  for_sum.sh #!/bin/bash #Author:wang sum=0 for i in {2..100..2} do let sum=$[sum+i] done echo $sum

 

 

 

 

 

 表示使用双括号括起来

[root@centos73 shell_scripts]# cat  for_sum.sh 
#!/bin/bash
#Author:wang

sum=0 for i in {2..100..2} do let sum=$((sum+i)) done echo $sum [root@centos73 shell_scripts]# bash for_sum.sh 2550

 

 

 

 

 

 

(二)求1到100被3整除的数字相加的和

 

 

把奇数偶数都加起来

求1到100被3整除的数字相加的和

和上面的脚本使用同样的套路

[root@centos73 shell_scripts]# echo   {3..100..3}
3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99
[root@centos73 shell_scripts]# cp    for_sum.sh   for_3sum.sh 
[root@centos73 shell_scripts]# vim  for_3sum.sh 
[root@centos73 shell_scripts]# bash  for_3sum.sh 
1683
[root@centos73 shell_scripts]# cat  for_3sum.sh 
#!/bin/bash
#Author:wang

sum=0
for   i  in  {3..100..3}


do 
     let  sum=$((sum+i))
done
echo  $sum

 

 

 

 

 

 

 

 

 

 

 

 

 

(三)求1到100不能被3整除的数字相加的和

 

 

判断对3取余数。

不等于有两种写法:

1[ ! "$yu" -eq 0 ]

2 [ "$yu" -ne 0 ]

 

法1:

[root@centos73 shell_scripts]# bash   for_3sum.sh 
3367
[root@centos73 shell_scripts]# cat   for_3sum.sh #!/bin/bash #Author:wang sum=0 for i in {1..100};do yu=$[i%3] if [ ! "$yu" -eq 0 ]; then
#注意这里是变量值最好加上双引号,不加也可以的。
let sum+=i fi done echo $sum

 

 

 

 

 

 

 

法2:

[root@centos73 shell_scripts]# bash    for_3sum.sh 
3367
[root@centos73 shell_scripts]# cat   for_3sum.sh #!/bin/bash #Author:wang sum=0 for i in {1..100};do yu=$[i%3] if [ "$yu" -ne 0 ]; then let sum+=i  fi
#注意写脚本要养成良好的习惯,比如缩进要美观。
done echo $sum

 

 

 

 

 

 

[root@centos73 shell_scripts]# bash    for_3sum.sh 
3367
[root@centos73 shell_scripts]# cat      for_3sum.sh #!/bin/bash #Author:wang sum=0 for i in {1..100};do yu=$[i%3] if [ $yu -ne 0 ]; then let sum+=i fi #注意写脚本要养成良好的习惯,比如缩进要美观。 done echo $sum

 

 

 

 

 

 

 

法3

[root@centos73 shell_scripts]# bash    for_3sum.sh 
3367
[root@centos73 shell_scripts]# cat    for_3sum.sh #!/bin/bash #Author:wang sum=0 for i in `seq 1 100`;do if [ $[i%3] -ne 0 ]; then let sum+=i fi done echo $sum [root@centos73 shell_scripts]# vim for_3sum.sh [root@centos73 shell_scripts]# bash for_3sum.sh 3367 [root@centos73 shell_scripts]# cat for_3sum.sh #!/bin/bash #Author:wang sum=0 for i in `seq 1 100`;do if [ "$[i%3]" -ne 0 ]; then let sum+=i fi done echo $sum

 

 

 

 

 

 

 

 

 

 

(四)添加10个用户user91-user100,密码为8位随机字符

 

 

创建用户,并且每个用户设置初始口令,口令是随机的,并且放到文件里面。

 具体问题可以表现为添加10个用户user91-user100,密码为8位随机字符

 

完整脚本

[root@centos73 shell_scripts]# cat   user_add.sh 
#!/bin/bash
#Author=wang
for i in `seq 91 100` ; do username=user$i useradd $username echo `openssl rand -base64 10| head -c 8` | passwd $username --stdin &>/dev/null done echo "finished"

 

 

 

 

 

 

执行结果

[root@centos73 shell_scripts]# bash user_add.sh 
finished

 

 

 

 

 

[root@centos73 shell_scripts]# cat  /etc/passwd |  tail
user91:x:1038:1038::/home/user91:/bin/bash user92:x:1039:1039::/home/user92:/bin/bash user93:x:1040:1040::/home/user93:/bin/bash user94:x:1041:1041::/home/user94:/bin/bash user95:x:1042:1042::/home/user95:/bin/bash user96:x:1043:1043::/home/user96:/bin/bash user97:x:1044:1044::/home/user97:/bin/bash user98:x:1045:1045::/home/user98:/bin/bash user99:x:1046:1046::/home/user99:/bin/bash user100:x:1047:1047::/home/user100:/bin/bash [root@centos73 shell_scripts]# 

 

 

 

 

[root@centos73 shell_scripts]# cat  /etc/shadow  | tail
user91:$6$YCyBiaF/$vovuieWrGWXwhHpRwsuJc85JOlFwvrUG/hNiPyLsJkHgWQG2v4oTE.B/CRANjcOhDkHlylH3iBG4bggmzstO40:18076:0:99999:7::: user92:$6$mxAMFuM1$.PqkWeHq231BmmnYcglitPkK/b4KOTcwLkO.S7isn9TA6ToN/sFR5ASwVF9HCHilEArql5R1Z4md6.auRaYj..:18076:0:99999:7::: user93:$6$Ga0/IYjR$TfriwLrqxYsdTlfoRRDNDn8gFwajOkxc5McuxTwoIKGAgWrI8NiKA6ASi4IdYuI7iQ/c2LL4mAte/JCj8juS0.:18076:0:99999:7::: user94:$6$E9mnyuH7$HS/TqWuhn8E8DX/ghu2SSOohcJU4LfACYg/hmrW9KIc4wZlsN5e.1.Q1ezNSY/w7WyRYYV2c6A2ofUBau/Csj1:18076:0:99999:7::: user95:$6$J.ljQLDk$6NvXXxx58y7487X0yMIQneF0dZKaqswiWigTu9xwJ1njIQmijvrhCkpxPL6ITJGdMB/j8.tYddIzMcUwWGnUv0:18076:0:99999:7::: user96:$6$uomIKnzW$9Llzo.qKU9rwcOpU68B7Sml28HUkM1AY06D1k7q7dpITxCdY3IFWWrK11tpwa6SVv4Z.lOiZ.0qgwaq/MNrnz0:18076:0:99999:7::: user97:$6$NRvTnViz$11cdhUq/9eVRj2SX85HrA/pNyYwqNsNOSObShmBljygjb9wzEZaJ8nPim8ZIGum.DUgG1ni2N3OgukKJmXYbI.:18076:0:99999:7::: user98:$6$40KBqdzU$.zsRi7sIxmVd4NAH7v5UYiQmvTxNlBMjKrddE3li/dtMxoS6TUHq0mK7XQRu.j6p7WjIxhkOZRmJULDssvEwB0:18076:0:99999:7::: user99:$6$y2efTk7A$4e4IX9muy30fO6Vv2Q75sAPCrY1XDZecEqxV6f7ZJJPg4V6FpVvIV/lamVaAiSnMQtL1LtGPbSYOu3KWReVFZ1:18076:0:99999:7::: user100:$6$tlPd3FrP$74gH4aqmlZ3xvp3TbaHSlWMkuDHDVJpr2XARz0n46Wf7Ni3zk9Eei83NhZISw64NvjI/a.YaM5y7d0ypPrrDw.:18076:0:99999:7:::

 

 

 

 

 

 

 

脚本解析

生成随机口令并且作为创建用户的口令

把改口令成功的提示放到黑洞里面去。

 echo `openssl rand -base64 10| head -c 8` | passwd $username --stdin &>/dev/null

 

 

 

 

[root@centos73 shell_scripts]# openssl rand -base64 10
Ey0PRDELAhuCfw==
[root@centos73 shell_scripts]# openssl rand -base64 10
Th1mFK8i95hJOQ== [root@centos73 shell_scripts]# openssl rand -base64 Usage: rand [options] num where options are -out file - write to file -engine e - use engine e, possibly a hardware device. -rand file:file:... - seed PRNG from files -base64 - base64 encode output -hex - hex encode output

 

 

 

 

 

 

提示符和命令都打印出来了

head -c 8表示获取前几个字节

[root@centos73 shell_scripts]# openssl rand -base64 10| head -c 8
bZ4p1m1N[root@centos73 shell_scripts]# openssl rand -base64 10| head -c 8 4z3GSMHZ[root@centos73 shell_scripts]# openssl rand -base64 10| head -c 8 W2c+6e/b[root@centos73 shell_scripts]# openssl rand -base64 10| head -c 8;echo qBPnSsJt

 

 

 

 

 

 

只显示命令的结果,在命令后面加上echo就可以了

[root@centos73 shell_scripts]# openssl rand -base64 10| head -c 8;echo 
cQJIkYwR
[root@centos73 shell_scripts]# openssl rand -base64 10| head -c 8;echo W+EX9dLc [root@centos73 shell_scripts]# openssl rand -base64 10| head -c 8;echo id5+GUME

 

 

 

 

 

[root@centos73 shell_scripts]# cat  for1.sh  -A
#!/bin/bash$
#Author:wang$
for   num  in {10..2..1}$ #M-eM-^FM-^YM-eM-.M-^L4M-dM-8M-*M-fM-^UM-0M-eM-0M-1M-dM-<M-^ZM-fM-^IM-'M-hM-!M-^L4M-fM-,M-!M-eM->M-*M-gM-^NM-/$ $ do $ echo "num is $num"$ done$ [root@centos73 shell_scripts]# cat for1.sh #!/bin/bash #Author:wang for num in {10..2..1} #写完4个数就会执行4次循环 do echo "num is $num" done

 

 

 

 

 

 

 

 

 

(五)定义网段的IP地址,测试其在是否开机启动

 

完整脚本

[root@centos73 shell_scripts]# cat   scan_ip.sh 
#!/bin/bash
#Author=wang
net=192.168.137 for i in {1..6};do if ping -c1 -w1 $net.$i &> /dev/null;then echo $net.$i is up echo $net.$i >> /app/ip.log else echo $net.$i is down fi done #如果ping通了就显示其为开机的,并且放到文件里面去。 #如果ping不通就执行下一次循环。

 

 

 

 

 

 

执行结果

[root@centos73 shell_scripts]# vim   scan_ip.sh
[root@centos73 shell_scripts]# bash  scan_ip.sh 
192.168.137.1 is up 192.168.137.2 is down 192.168.137.3 is down 192.168.137.4 is down 192.168.137.5 is down 192.168.137.6 is down 

 

 

 

 

 

 

 

脚本解析

net=192.168.137表示网络位,子网掩码是24

主机位for i in {1..6};do,我只选取了几台主机

ping -c1 -w1   $net.$i 因为涉及两个变量,都要加上$

 

 

 

 

 

 在运行的其实是网关

[root@centos73 shell_scripts]# cat  /app/ip.log 
192.168.137.1

 

 

 

 

 

 

bug1: 

脚本的执行效率不高,解决办法就是在后台执行

[root@centos73 shell_scripts]# ping  192.168.137.1    -c3    &
[1] 1288 [root@centos73 shell_scripts]# PING 192.168.137.1 (192.168.137.1) 56(84) bytes of data. 64 bytes from 192.168.137.1: icmp_seq=1 ttl=128 time=0.190 ms 64 bytes from 192.168.137.1: icmp_seq=2 ttl=128 time=0.091 ms 64 bytes from 192.168.137.1: icmp_seq=3 ttl=128 time=0.158 ms --- 192.168.137.1 ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2000ms rtt min/avg/max/mdev = 0.091/0.146/0.190/0.042 ms

 

 

 

 

 

 

bug2:

 在后台执行不回车不会退出来,在脚本里面也是一样的

[root@centos73 shell_scripts]# ping  192.168.137.1    -c3    &   wait
[1] 1319 PING 192.168.137.1 (192.168.137.1) 56(84) bytes of data. 64 bytes from 192.168.137.1: icmp_seq=1 ttl=128 time=0.529 ms 64 bytes from 192.168.137.1: icmp_seq=2 ttl=128 time=0.131 ms 64 bytes from 192.168.137.1: icmp_seq=3 ttl=128 time=0.111 ms --- 192.168.137.1 ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2001ms rtt min/avg/max/mdev = 0.111/0.257/0.529/0.192 ms [1]+ Done ping 192.168.137.1 -c3

 

 

 

 

[root@centos73 shell_scripts]# cat  scan_ip.sh 
#!/bin/bash
#Author=wang
net=192.168.137 for i in {1..6};do { if ping -c1 -w1 $net.$i &> /dev/null;then echo $net.$i is up echo $net.$i >> /app/ip.log else echo $net.$i is down fi }& done [root@centos73 shell_scripts]# 192.168.137.1 is up 192.168.137.2 is down 192.168.137.3 is down 192.168.137.6 is down 192.168.137.5 is down 192.168.137.4 is down ^C

 

 

 

 

 

 

解决办法加上wait

现在执行效率提高了并且会退出

[root@centos73 shell_scripts]# bash  scan_ip.sh 
192.168.137.1 is up
192.168.137.2 is down 192.168.137.4 is down 192.168.137.3 is down 192.168.137.5 is down 192.168.137.6 is down [root@centos73 shell_scripts]# cat scan_ip.sh #!/bin/bash #Author=wang net=192.168.137 for i in {1..6};do { if ping -c1 -w1 $net.$i &> /dev/null;then echo $net.$i is up echo $net.$i >> /app/ip.log else echo $net.$i is down fi }& done wait #如果ping通了就显示其为开机的,并且放到文件里面去。 #如果ping不通就执行下一次循环。

 

 

 

 

 

 

bug3:

因为前面多次执行了脚步,在文件里面会生成重复的内容

[root@centos73 shell_scripts]# cat  /app/ip.log 
192.168.137.1
192.168.137.1 192.168.137.1

 

 

 

 

 

 

解决办法在脚本的第1行先清空文件内容?

[root@centos73 shell_scripts]# bash  scan_ip.sh 
192.168.137.1 is up
192.168.137.6 is down 192.168.137.5 is down 192.168.137.2 is down 192.168.137.4 is down 192.168.137.3 is down [root@centos73 shell_scripts]# cat /app/ip.log 192.168.137.1 [root@centos73 shell_scripts]# cat scan_ip.sh #!/bin/bash #Author=wang > /app/ip.log net=192.168.137 for i in {1..6};do { if ping -c1 -w1 $net.$i &> /dev/null;then echo $net.$i is up echo $net.$i >> /app/ip.log else echo $net.$i is down fi }& done wait #如果ping通了就显示其为开机的,并且放到文件里面去。 #如果ping不通就执行下一次循环。

 

 

 

 

 

 

 查看开机运行的主机的信息

[root@centos73 shell_scripts]#   nmap    -v  -A   192.168.137.1

Starting Nmap 6.40 ( http://nmap.org ) at 2019-02-09 23:35 CST NSE: Loaded 110 scripts for scanning. NSE: Script Pre-scanning. Initiating ARP Ping Scan at 23:35 Scanning 192.168.137.1 [1 port] Completed ARP Ping Scan at 23:35, 0.01s elapsed (1 total hosts) Initiating Parallel DNS resolution of 1 host. at 23:35 Completed Parallel DNS resolution of 1 host. at 23:35, 0.08s elapsed Initiating SYN Stealth Scan at 23:35 Scanning 192.168.137.1 [1000 ports] Discovered open port 53/tcp on 192.168.137.1 Completed SYN Stealth Scan at 23:35, 0.14s elapsed (1000 total ports) Initiating Service scan at 23:35 Scanning 1 service on 192.168.137.1 Completed Service scan at 23:35, 1.24s elapsed (1 service on 1 host) Initiating OS detection (try #1) against 192.168.137.1 Retrying OS detection (try #2) against 192.168.137.1 NSE: Script scanning 192.168.137.1. Initiating NSE at 23:35 Completed NSE at 23:35, 5.17s elapsed Nmap scan report for 192.168.137.1 Host is up (0.047s latency). Not shown: 999 closed ports PORT STATE SERVICE VERSION 53/tcp open tcpwrapped MAC Address: 00:50:56:E2:3D:B6 (VMware)
Aggressive OS guesses: Microsoft Windows 7 Enterprise (93%), Microsoft Windows XP SP3 (93%), DD-WRT v24-sp2 (Linux 2.4.37) (91%),
DVTel DVT-9540DW network camera (91%), Linux 3.2 (90%), BlueArc Titan 2100 NAS device (89%), Brother HL-5170DN printer (88%),
Pirelli DP-10 VoIP phone (88%), Aethra Starvoice 1042 ADSL router (87%), Brother HL-1870N printer (87%) No exact OS matches for host (test conditions non-ideal). Network Distance: 1 hop TCP Sequence Prediction: Difficulty=257 (Good luck!) IP ID Sequence Generation: Incremental TRACEROUTE HOP RTT ADDRESS 1 46.57 ms 192.168.137.1 NSE: Script Post-scanning. Read data files from: /usr/bin/../share/nmap OS and Service detection performed. Please report any incorrect results at http://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 12.12 seconds Raw packets sent: 1044 (49.132KB) | Rcvd: 1036 (42.012KB)

 

 

 

 

 

法2:

把网段写死了,设置要扫描的网段是变化的,或者说是交互式的。

如果用户不是输入IP地址,那就要温馨提示请输入正确的地址

判断是否是IP地址可以使用正则表达式

[root@centos73 shell_scripts]# bash  scan_ip.sh 
192.168.137.1 is up
192.168.137.4 is down 192.168.137.2 is down 192.168.137.6 is down 192.168.137.3 is down 192.168.137.5 is down [root@centos73 shell_scripts]# cat /app/ip.log 192.168.137.1 is up [root@centos73 shell_scripts]# cat scan_ip.sh #!/bin/bash #Author=wang > /app/ip.log net=192.168.137 for i in {1..6};do { if ping -c1 -w1 $net.$i &> /dev/null;then echo $net.$i is up | tee -a /app/ip.log else echo $net.$i is down fi }& done wait #如果ping通了就显示其为开机的,并且放到文件里面去。 #如果ping不通就执行下一次循环。

 

 

 

 

 

 

 

ip="114.122.2.255";[[ "$ip" =~ ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$ ]] && echo true ||echo false

 

[root@centos73 shell_scripts]# bash  scan_ip.sh 
please   input   the   network(eg:192.168.137.0):1.1.1.1 scan_ip.sh: line 8: syntax error near unexpected token `||' scan_ip.sh: line 8: `|| { echo "please input a legal IP";exit 1 ;}'  [root@centos73 shell_scripts]# cat scan_ip.sh #!/bin/bash #Author=wang > /app/ip.log net=192.168.137 read -p "please input the network(eg:192.168.137.0):" network [[ "$network" =~ ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$ ]] || { echo "please input a legal IP";exit 1 ;} #||是不能写在开头的 for i in {1..6};do { if ping -c1 -w1 $net.$i &> /dev/null;then echo $net.$i is up | tee -a /app/ip.log else echo $net.$i is down fi }& done wait

 

 

 

 

 

 


[root@centos73 shell_scripts]# bash  scan_ip.sh 
please   input   the   network(eg:192.168.137.0):1 please input a legal IP [root@centos73 shell_scripts]# bash scan_ip.sh  please input the network(eg:192.168.137.0):1.1.1.1 192.168.137.1 is up 192.168.137.5 is down 192.168.137.3 is down 192.168.137.6 is down 192.168.137.2 is down 192.168.137.4 is down [root@centos73 shell_scripts]# cat /app/ip.log 192.168.137.1 is up [root@centos73 shell_scripts]# cat scan_ip.sh #!/bin/bash #Author=wang > /app/ip.log net=192.168.137 read -p "please input the network(eg:192.168.137.0):" network [[ "$network" =~ ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$ ]] || { echo "please input a legal IP";exit 1 ;} for i in {1..6};do { if ping -c1 -w1 $net.$i &> /dev/null;then echo $net.$i is up | tee -a /app/ip.log else echo $net.$i is down fi }& done wait #如果ping通了就显示其为开机的,并且放到文件里面去。 #如果ping不通就执行下一次循环。 #地址输入了之后要判断是否是一个地址,使用正则表达式

 

 

 

 

 只要前3段

[root@centos73 shell_scripts]# bash  scan_ip.sh    
please   input   the   network(eg:192.168.137.0):192.168.137.4 192.168.137.1 is up 192.168.137.5 is down 192.168.137.3 is down 192.168.137.6 is down 192.168.137.2 is down 192.168.137.4 is down [root@centos73 shell_scripts]# bash scan_ip.sh please input the network(eg:192.168.137.0):3 please input a legal IP [root@centos73 shell_scripts]# bash scan_ip.sh please input the network(eg:192.168.137.0):1.1.1.1 1.1.1.1 is up 1.1.1.2 is down 1.1.1.4 is down 1.1.1.5 is down 1.1.1.3 is down 1.1.1.6 is down [root@centos73 shell_scripts]# cat /app/ip.log 1.1.1.1 is up [root@centos73 shell_scripts]# ping 1.1.1.1 PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data. 64 bytes from 1.1.1.1: icmp_seq=1 ttl=128 time=11.2 ms 64 bytes from 1.1.1.1: icmp_seq=2 ttl=128 time=9.84 ms 64 bytes from 1.1.1.1: icmp_seq=3 ttl=128 time=12.7 ms 64 bytes from 1.1.1.1: icmp_seq=4 ttl=128 time=11.2 ms 64 bytes from 1.1.1.1: icmp_seq=5 ttl=128 time=10.0 ms 64 bytes from 1.1.1.1: icmp_seq=6 ttl=128 time=10.8 ms 64 bytes from 1.1.1.1: icmp_seq=7 ttl=128 time=11.5 ms 64 bytes from 1.1.1.1: icmp_seq=8 ttl=128 time=9.92 ms ^C --- 1.1.1.1 ping statistics --- 8 packets transmitted, 8 received, 0% packet loss, time 7015ms rtt min/avg/max/mdev = 9.847/10.923/12.709/0.912 ms 

 

 

 

 

 

 

 

 

[root@centos73 shell_scripts]# cat  scan_ip.sh    
#!/bin/bash
#Author=wang

> /app/ip.log net=192.168.137
#这行是可以不要的,但是因为后面的变量会覆盖的,所以保留也不影响的。
read -p "please input the network(eg:192.168.137.0):" network [[ "$network" =~ ^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$ ]] || { echo "please input a legal IP";exit 1 ;} net=`echo $network | cut -d. -f1-3` for i in {1..6};do { if ping -c1 -w1 $net.$i &> /dev/null;then echo $net.$i is up | tee -a /app/ip.log else echo $net.$i is down fi }& done wait #如果ping通了就显示其为开机的,并且放到文件里面去。 #如果ping不通就执行下一次循环。 #地址输入了之后要判断是否是一个地址

 

转载于:https://www.cnblogs.com/wang618/p/11109287.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值