编写脚本/root/bin/hostping.sh,接受一个主机的IPv4地址做为参数,测试是否可连通。如果能ping通,则提示用户“该IP地址可访问”;如果不可ping通,则提示用户“该IP地址不可访问”

1、提示用户输入IP

read -p "IPv4:" ip

2、判断变量$ip是否为合法ip,如果是,则提示ip合法;如果否,则输出“请输入正确的ip。”并退出。

[[ $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])$ ]] && [ $ip2 = $ip ] && echo "The IP address can be accessed." || ( echo "Please enter the correct IP." & exit 1 )

3、ping ip一次,取第二行的ip,并定义为变量$ip2

ip2=ping $ip -c1|head -2|tail -1|tr -s' ' :|cut -d: -f4

4、判断变量$ip2是否等于变量$ip,如果是,则输出“此ip可以ping通。”;如果否,则输出“此ip无法ping通。”

[ $ip2 = $ip ] && echo "The IP address can be accessed." || echo "No"