Shell腳本 – 查看網(wǎng)絡(luò)接口信息
本文介紹如何是用shell腳本查看網(wǎng)絡(luò)接口的ip地址、MAC地址、網(wǎng)絡(luò)速率等信息。
系統(tǒng)環(huán)境
Centos7
1)檢查可用的網(wǎng)絡(luò)接口
使用ip和awk命令,過濾出狀態(tài)為UP的網(wǎng)絡(luò)接口。
- [root@localhost ~]# ip ad|awk '/state UP/ {print $2}'
- ens33:
- ens38:
2)查看網(wǎng)絡(luò)接口的IP地址
使用下面命令過濾出每個(gè)接口的ip地址:
- [root@localhost ~]# ip -o addr |awk '/inet/{print $2,$4}'
- lo 127.0.0.1/8
- lo ::1/128
- ens33 192.168.43.138/24
- ens33 fe80::214e:53b4:43f6:5495/64
- ens38 172.25.254.130/24
- ens38 fe80::c2ff:9dbc:76be:6dd9/64
- 或者只查看IPv4地址:
- [root@localhost ~]# ip addr | grep inet|grep -v 'inet6'|awk '{print $NF, $2}'
- lo 127.0.0.1/8
- ens33 192.168.43.138/24
- ens38 172.25.254.130/24
3)查看網(wǎng)卡的MAC地址
如果只想查看網(wǎng)絡(luò)接口名稱和相應(yīng)的MAC地址,請使用以下命令。檢查特定的網(wǎng)絡(luò)接口的MAC地址:
- [root@localhost ~]# ip link show ens33 | awk '/link/{print $2}'
- 00:0c:29:99:ee:d9
查看所有網(wǎng)絡(luò)接口的MAC地址,可以寫一個(gè)腳本來實(shí)現(xiàn):
- [root@localhost ~]# cat mac-address.sh
- #!/bin/bash
- ip addr |awk '/state UP/{print $2}' | sed 's/://' | while read output
- do
- echo $output:
- ethtool -P $output
- done
查看一下運(yùn)行結(jié)果:
4)查看網(wǎng)絡(luò)接口的速度
如果要在Linux上檢查網(wǎng)絡(luò)接口端口速度,可以使用ethtool工具。下面是查看特定網(wǎng)絡(luò)接口的速度:
- [root@localhost ~]# ethtool ens33|grep "Speed:"
- Speed: 1000Mb/s
查看所有接口的網(wǎng)絡(luò)速度,可以寫一個(gè)腳本來實(shí)現(xiàn):
- [root@localhost ~]# cat port-speed.sh
- #!/bin/bash
- ip addr |awk '/state UP/{print $2}' | sed 's/://' | while read output
- do
- echo $output:
- ethtool $output |grep "Speed:"
- done
查看一下運(yùn)行結(jié)果:
5)查看網(wǎng)絡(luò)接口信息的Shell腳本
下面這個(gè)腳本,我們來實(shí)現(xiàn)查看主機(jī)名、IPv4、IPv6、MAC地址、網(wǎng)絡(luò)接口速度信息:
- [root@localhost ~]# cat nic-info.sh
- #!/bin/bash
- hostname
- echo "-------------"
- for iname in $(ip addr |awk '/state UP/{print $2}')
- do
- echo "$iname"
- ip addr show $iname | grep inet | awk '{printf "%s:\t%s\n",$1,$2}'
- ip link show $iname | grep link | awk '{printf "MAC:\t%s\n",$2}'
- ethtool ens33 | awk '/Speed/{printf "%s\t%s\n",$1,$2}'
- done
本文轉(zhuǎn)載自微信公眾號「Linux就該這么學(xué)」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系Linux就該這么學(xué)公眾號。