ifconfig eth0 | grep -E 'inet addr:|inet 地址:' | awk '{print $2}' | cut -c 6- (獲取eth0網卡的IP地址)
ifconfig eth0 | grep "HWaddr" | awk '{print $5}' (獲取eth0網卡的MAC地址)
上面的腳本分解步驟是:
- 獲取eth0網卡的信息
- 過濾出IP地址的行或MAC地址的行
- 使用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