您的位置:首页 > 运维架构 > Shell

BASH第七课第一题

2015-08-24 09:27 579 查看
1、写一个脚本getinterface.sh,脚本可以接受参数(i,I,a),完成以下任务:

(1)使用以下形式:getinterface.sh [-i interface|-I IP|-a]

(2)当用户使用-i选项时,显示其指定网卡的IP地址;

(3)当用户使用-I选项时,显示其后面的IP地址所属的网络接口;(如 192.168.199.183:eth0)

(4)当用户单独使用-a选项时,显示所有网络接口及其IP地址(lo除外)

#!/bin/bash

exec 2>>/dev/null
command=$1
list=`netstat -i | sed -n '3,65535p'|awk -F" " '{print $1}'`
[ -z $command ]&&command="-h"

function helptext()
{
echo "getinterface.sh[-i interface|-I IP|-a|-h]"
echo "-----------------------------------------"
echo "-i interface (show ip of the interface)"
echo "-I IP (show interface of the IP)"
echo "-a list all interfaces and their IPs"
echo "-h show the help text"
echo "-----------------------------------------"
}
if [ $command == "-h" ];then
helptext
elif [ $command == "-i" ];then
interface=$2
ifconfig $interface >/dev/null
flag=$?
if [ -z $interface ]; then
echo "please input the interface"
exit 2
elif [ $flag -ne 1 ];then
ip=`ifconfig $interface | grep "inet addr" | awk -F" " '{print $2}' | awk -F":" '{print $2}'`
echo "$interface $ip"
else
echo "$interface is not exist"
fi
elif [ $command == "-I" ];then
IP=$2
if [ -z $IP ]; then
echo "please input the IP"
exit 2
else
for inter in $list;
do
ip_temp=`ifconfig $inter | grep "inet addr" | awk -F" " '{print $2}' | awk -F":" '{print $2}'`
if [ $IP == $ip_temp ];then
echo "$IP : $inter"
exit 0
fi
done
fi
echo "$IP is not exist in the interfaces of  the device"
elif [ $command == "-a" ];then
for inter in $list;
do
ip_temp=`ifconfig $inter | grep "inet addr" | awk -F" " '{print $2}' | awk -F":" '{print $2}'`
if [ $inter != "lo" ];then
echo "$inter:$ip_temp"
fi
done
else
echo "the format error!!!"
helptext
fi
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: