学以致用二十-----试着写的第一个脚本

今天试着写了以第一个脚本。

脚本的目的是第一次安装完系统后,自动获取ip地址。

脚本如下

  1 #!/usr/bin/bash
  2 #check command ifconfig is right or not found
  3 #check ip dhcp
  4 
  5 net_path=/etc/sysconfig/network-scripts
  6 net_name=$(ls ${net_path} | grep -v 'o$' | grep 'ifcfg')
  7 eth_name=$(ls ${net_path} | grep -v 'o$' | grep 'ifcfg' | cut -c 7-)
  8 
  9 if ifconfig &>/dev/null;then
 10     net_config=$(ifconfig ${eth_name} | grep inet)
 11     if [ "${net_config}" = "" ];then
 12         sed -i 's/ONBOOT=no/ONBOOT=yes/g' ${net_path}/${net_name}
 13         service network restart
 14     else
 15         net_ip=$(ifconfig ${eth_name} | grep -v inet6 | grep inet | awk '{print $2}')
 16         echo "The ip is "$net_ip""
 17     fi
 18 else
 19     echo "ifconfig command not found"
 20 fi

思路:

1、最小化安装centos 7.2后,我发现执行ifconfig命令,会提示

因此在执行ifconfig的时候,做了个if判断

2、   net_name=$(ls ${net_path} | grep -v 'o$' | grep 'ifcfg')

网卡名称。我的虚拟机网卡名称

思路是通过grep 正则表达来查找 ifcfg开头的文件,但是查出来会有两个

当时想着用正则表达式,除去行尾为lo的表达式,试了一些方法没实现。于是采用grep自带的过滤功能,grep -v   

3、   eth_name=$(ls ${net_path} | grep -v 'o$' | grep 'ifcfg' | cut -c 7-)

ifconfig的参数不是带网卡名,不是  ifcofnig  ifcfg-eno16777728,而是  ifconfig  eno16777728

因此需要获取eno16777728这个字段,

思路,采用cut的方式,cut -c   以字符为单位进行分割 

范围控制:
    n:只有第n项
    n-:从第n项一直到行尾
    n-m:从第n项到第m项(包括m)
    -m:从一行的开始到第m项(包括m)
    -:从一行的开始到结束的所有项
ifcfg-eno16777728 -c 7- 可得到结果 eno16777728

4、 sed -i 's/ONBOOT=no/ONBOOT=yes/g' ${net_path}/${net_name}

sed 替换

5、 net_ip=$(ifconfig ${eth_name} | grep -v inet6 | grep inet | awk '{print $2}')

grep -v  过滤掉 inet6 结合 awk 打印出 ip地址

执行结果:

1、未获取ip的情况

2、 已经获取ip地址的情况

脚本基本实现了我的想法。

再接再厉,多练习,脚本不像想象当中那么复杂。

猜你喜欢

转载自www.cnblogs.com/liongong/p/9791637.html
今日推荐