ipAllocate_and_linkState_hacking

  1 #!/bin/bash
  2 # Author: Joshua Chen
  3 # Date: Jun 2014
  4 # Location: Shenzhen
  5 
  6 #1. 解读这两个程序是因为程序中包含了大部分shell脚本的基本语法;
  7 #2. 省去以后需要使用到shell脚本的时候,需要参考的需求;
  8 #3. 在本代码中,以24位掩码为基准,如果IP为: 10.1.1.7,那么前面三位数是网络位: 10.1.1,最后一位是主机位: 7
  9 #                                     2015-3-28 晴 深圳 曾剑锋
 10 
 11 
 12 # Description: allocate IPs to students
 13 
 14 #每个人分配一个主IP, 3个辅助IP
 15 EXTRA_COUNT=3        
 16 #IP的前缀,相当这个脚本用于分配10.1.1段的IP,也就是网络位
 17 IP_PREFIX=10.1.1     
 18 #最多分配50个主IP
 19 MAX_GRP=50           
 20 #主IP的主机位从11开始
 21 PRIM_MIN=11          
 22 #主IP的主机位最大值
 23 PRIM_MAX=$((PRIM_MIN + MAX_GRP -1))     
 24 #扩展IP的主机位最小值
 25 EXTRA_MIN=$((PRIM_MAX + 1))             
 26 #扩展IP的主机位最大值
 27 #EXTRA_MAX=$((EXTRA_MIN + MAX_GRP * EXTRA_COUNT -1)) 
 28 
 29 #获取传入的第一个参数,如果文件不存在,那个就退出,
 30 #并且打印出命令的使用方法.
 31 list=$1
 32 if [ ! -e "$list" ];then
 33     #输出到标准错误输出
 34     echo "Can not locate list file '$list'" >&2 
 35     #需要传入有学生姓名的文件,每个学生名字占一行
 36     echo "Usage: $(basename $0) <name list>"
 37     exit 1
 38 fi
 39 
 40 #检查list路径下文件的行数是否大于MAX_GRP,以下提供2种写法
 41 #if [ $(wc -l "$list" | cut -d " " -f1) -gt "$MAX_GRP" ];then
 42 if [ $(wc -l < "$list") -gt "$MAX_GRP" ];then
 43     echo "Too many entries in the name list! maximum $MAX_GRP is allowed" >&2
 44     exit 1
 45 fi
 46 
 47 #分配主IP
 48 #每次从list代表的文件中读取一行名字,保存在name的变量中,
 49 #然后是用printf组合分配IP.
 50 echo "------- Primary IP -------"
 51 n=$PRIM_MIN
 52 while read name
 53 do
 54     printf "%s.%-3s %s
" "${IP_PREFIX}" $n "$name"
 55     ((n++)) #语法要求,这样就可以像写C一样
 56 done < "$list"
 57 
 58 #分配辅助IP
 59 #因为辅助IP这里需要分配3个,所以while里面再是用for循环
 60 #对IP进行分配.
 61 echo
 62 echo "------- Extra IP -------"
 63 n=$EXTRA_MIN
 64 while read name
 65 do
 66     for i in $(seq $EXTRA_COUNT) #seq用于产生序列供for循环使用
 67     do
 68         printf "%s.%-3s %s
" "${IP_PREFIX}" $n "$name"
 69         ((n++))
 70     done
 71 done < "$list"
 72 
 73 #退出程序
 74 exit 0
 75 
 76 
 77 # Description: detect the ethernet link state
 78 
 79 #网卡设备所在的目录
 80 dir=/sys/class/net
 81 #文件名carrier
 82 file=carrier
 83 
 84 # need root privilege
 85 if [ "$UID" -ne 0 ]; then
 86     echo "Must be root"
 87     exit 1
 88 fi
 89 
 90 if [ ! -d $dir ];then
 91     echo "Directory $dir doesn't exist, quit."
 92     exit 1
 93 fi
 94 
 95 cd $dir
 96 
 97 
 98 # do we have an NIC? #Network Interface Card
 99 if ! ls | grep -q ^eth; then
100     echo "No NIC detected"
101     exit 1
102 fi
103 
104 # check the status of each NIC
105 ls | grep ^eth | while read dev
106 do
107     # take it up first
108     ifconfig $dev up &> /dev/null
109 
110     # if the file is not found and put error to /dev/null
111     if [ "$(cat $dev/$file 2>/dev/null)" = "1" ];then
112         echo "$dev: link ok"
113     else
114         echo "$dev: no link"
115     fi
116 done
117 
118 exit 0
原文地址:https://www.cnblogs.com/zengjfgit/p/4374877.html