社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
我使用的Linux服务器上有多个网卡,有时候就需要在脚本中使用到指定网卡的IP地址或MAC地址,那么这个时候就有两种做法,一是预先读取网卡的IP地址或MAC地址,然后写入到脚本中;另外一种方法就是通过shell命令实时获取指定网卡上的当前IP地址或MAC地址。
上面的脚本的分解步骤是:
先看一下ifconfig的man手册中的描述:
Ifconfig is used to configure the kernel-resident network interfaces.
If no arguments are given, ifconfig displays the status of the currently active interfaces. If a single
interface argument is given, it displays the status of the given interface only; if a single -a argument is
given, it displays the status of all interfaces, even those that are down.
ifconfig命令的主要作用是进行网卡配置,但是如果没有给定参数或者只是给定了网卡名称这一个参数,则就会显示网卡的状态信息。
因此,在这里,我们通过参数eth0来指定输出该网卡的信息。
我们先看一下ifconfig的输出格式:
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
inet6 addr: fe80::a00:27ff:fef6:188e/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:12575 errors:0 dropped:0 overruns:0 frame:0
TX packets:3429 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1931585 (1.9 MB) TX bytes:465667 (465.6 KB)
其中红色部分中包含了MAC地址信息,蓝色部分包含了IPv4的地址信息。而如果我们指定的网卡不存在时,则输出信息如下:
nfer@nfer:~$ ifconfig eth1
eth1: error fetching interface information: Device not found
因此在上面的命令中,我们分别使用grep "inet addr:"和grep "HWaddr"来过滤出IPv4的地址和MAC地址所在的行,如果是该网卡不存在或者不处于活动状态就过滤不到对应的行。
在上面的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-。
一个开卷有益的公众号:IT平头哥
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!