46.輸入網卡顯示ipaddr,輸入ip顯示網卡腳本

思路:先將網卡和對應IP地址寫入到文本,再根據輸入的參數進行case判斷
#!/bin/bash
eths=/tmp/eths.txt #定義網卡文本路徑
eth_if=/tmp/eth_if.txt#定義網卡和對應IP地址的文本路徑
useage() {
  echo "please input: $0 -i network card or -I ip address."
}#定義使用函數

wrong_netcard() {
  if ! awk -F ':' '{print $1}' $eth_if|grep -qw "^$1$";then
    #第一個$1爲awk參數,第二個$1爲外部傳參參數$2賦值,"^ $"以參數開頭結束
        echo "please input right network information: `awk -F ':' '{print $1}' $eth_if|xargs`"
                #|xargs網卡信息不換行輸出
        exit#退出腳本
  fi
}#定義錯誤網卡函數

wrong_ip() {
  if ! awk -F ':' '{print $2}' $eth_if|grep -qw "^$1$";then
        echo -e "please input correct ip address: \n`awk -F ':' '{print $2}' $eth_if|grep -v '^$'`"
                #echo -e  "\n"換行,grep -v '^$'將空行過濾
        exit#退出腳本
  fi
}#定義錯誤ip地址函數

ip addr |awk -F ': ' '$1 ~ "^[0-9]" {print $2}' > $eths
for i in `cat $eths`
do
         ip_1=`ip addr |grep  -A2 ": $i:"| grep -w inet|awk '{print $2}'|cut -d '/' -f1`
         echo "$i:$ip_1" >> $eth_if
done #將系統網卡對應信息寫入到$eth_if文本
[ -f $eths ] && rm $eths #刪除文本
if [ $# -ne 2 ];then #判斷傳遞參數爲2
        useage
        exit#退出腳本
fi
case $1 in
        -i)
        wrong_netcard $2
        eth_ip=`grep -w $2 $eth_if |awk -F ':' '{print $2}'`
    if [ -z $eth_ip ];then#判斷網卡ip爲空
        echo "$2 ip address is none!"
        else
        echo "$2 ip address is $eth_ip"
        fi
        ;;
        -I)
        wrong_ip $2
        ip_eth=`grep -w $2 $eth_if |awk -F ':' '{print $1}'`
        echo "$2 network card information is $ip_eth"
        ;;
        *)
        useage
        ;;
esac
[ -f $eth_if ] && rm $eth_if#刪除文本

使用網卡:sh getinterface.sh -i br0
輸出信息:br0 ip address is 192.168.32.139

使用IP:sh getinterface.sh -I 127.0.0.1
輸出信息:127.0.0.1 network card information is lo
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章