BASH第七课第一题

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


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值