脚本获取eth0网卡ip地址

ifconfig eth0 | grep -E 'inet addr:|inet 地址:' | awk '{print $2}' | cut -c 6-  (获取eth0网卡的IP地址)

ifconfig eth0 | grep "HWaddr" | awk '{print $5}'  (获取eth0网卡的MAC地址)

上面的脚本分解步骤是:

  1. 获取eth0网卡的信息
  2. 过滤出IP地址的行或MAC地址的行
  3. 使用awk输出指定字段,对于MAC地址,第5个字段就是MAC;而对于IP地址,还需要对第2个字段截取第6个字符之后的内容

awk命令和cut命令部分说明

在上面的grep命令过滤出来的MAC地址和IPv4地址所在行的格式如下:

eth0      Link encap:Ethernet  HWaddr 08:00:27:f6:18:8e  
          inet addr:192.168.56.101  Bcast:192.168.56.255  Mask:255.255.255.0

因此,如果是获取MAC地址,只需要使用awk输出第5个字段的值即可:awk '{print $5}';

而如果是要获取IPv4的地址,则需要先输出第2个字段的值:awk '{print $2}',然后再使用cut命令,将"addr:"这5个字符去除,即从第6个字符到结尾的所有字符:cut -c 6-。

其中cut命令的-c参数以及后面的需要显示的字符列表的表述方式的描述如下:

       -c, --characters=LIST
              select only these characters

 

Use one, and only one of -b, -c or -f.  Each LIST is made up of one range, or many ranges separated by commas.
       Selected  input  is written in the same order that it is read, and is written exactly once.  Each range is one of:
       N      N'th byte, character or field, counted from 1
       N-     from N'th byte, character or field, to end of line
       N-M    from N'th to M'th (included) byte, character or field
       -M     from first to M'th (included) byte, character or field

我们这里是按照字符操作的,所以使用了-c参数;需要显示的是从第6个字符到结尾的部分,所以使用了N-的模式表示LIST。

 

 

参考资料:http://blog.csdn.net/nfer_zhuang/article/details/42609733

posted @ 2017-07-05 14:20  javadongx  阅读(1954)  评论(0编辑  收藏  举报

javadong@qq.com