写一个脚本:
ping命令去查看172.16.1.1-172.16.67.1范围内的所有主机是否在线;在线的显示为up, 不在线的显示down,分别统计在线主机,及不在线主机数;
分别使用for, while和until循环实现。
#!/bin/bash
#
declare -i uphosts=0
declare -i downhosts=0
for i in {1..17}; do
if ping -W 1 -c 1 172.16.$i.1 &> /dev/null; then
echo "172.16.$i.1 is up."
let uphosts+=1
else
echo "172.16.$i.1 is down."
let downhosts+=1
fi
done
echo "Up hosts: $uphosts, Down hosts: $downhosts."
#!/bin/bash
#
declare -i uphosts=0
declare -i downhosts=0
declare -i i=1
hostping() {
if ping -W 1 -c 1 $1 &> /dev/null; then
echo "$1 is up."
return 0
else
echo "$1 is down."
return 1
fi
}
while [ $i -le 67 ]; do
hostping 172.16.$i.1
[ $? -eq 0 ] && let uphosts++ || let downhosts++
let i++
done
echo "Up hosts: $uphosts, Down hosts: $downhosts."
写一个脚本,实现:
能探测C类、B类或A类网络中的所有主机是否在线;
#!/bin/bash
#
cping() {
local i=1
while [ $i -le 5 ]; do
if ping -W 1 -c 1 $1.$i &> /dev/null; then
echo "$1.$i is up"
else
echo "$1.$i is down."
fi
let i++
done
}
bping() {
local j=0
while [ $j -le 5 ]; do
cping $1.$j
let j++
done
}
aping() {
local x=0
while [ $x -le 255 ]; do
bping $1.$x
let x++
done
}
提示用户输入一个IP地址或网络地址;获取其网络,并扫描其网段;
信号捕捉:
列出信号:
trap -l
kill -l
man 7 signal
trap ‘COMMAND‘ SIGNALS
常可以进行捕捉的信号:
HUP, INT
示例:
#!/bin/bash
#
declare -a hosttmpfiles
trap ‘mytrap‘ INT
mytrap() {
echo "Quit"
rm -f ${hosttmpfiles[@]}
exit 1
}
for i in {1..50}; do
tmpfile=$(mktemp /tmp/ping.XXXXXX)
if ping -W 1 -c 1 172.16.$i.1 &> /dev/null; then
echo "172.16.$i.1 is up" | tee $tmpfile
else
echo "172.16.$i.1 is down" | tee $tmpfile
fi
hosttmpfiles[${#hosttmpfiles[*]}]=$tmpfile
done
rm -f ${hosttmpfiles[@]}
在bash中使用ACSII颜色
\033[31m hello \033[0m
##m:
左侧#:
3:前景色
4:背景色
右侧#:颜色种类
1, 2, 3, 4, 5, 6, 7
#m:
加粗、闪烁等功能;
多种控制符,可组合使用,彼此间用分号隔开;
dialog命令可实现窗口化编程;
各窗体控件使用方式;
如何获取用户选择或键入的内容?
默认,其输出信息被定向到了错误输出流;
《高级bash编程指南》,《Linux命令行和shell脚本编程宝典》
来源: