简体   繁体   中英

Linux Bash: List interfaces with IPs and Mac addresses

I am working on a CentOS. This is my first time messing around in a UNIX-based OS, and having a hard time getting used to it. I have more solid experience with Powershell. Anyway, my task is to list all the Interfaces and their corresponding IP and MAC addresses. Is there a simple way to do this? I discovered that

ip addr

apparently has all the information I need, but I have no idea how could I "cut out" the information I need from the string. I want to list them in some readable format, like this:

interfacename       ipaddress         macaddress

Write a script like this:

#!/bin/bash

printf '%10s %32s %32s\n' interface ipaddress macaddress
printf '%s\n' '----------------------------------------------------------------------------'
for each in $(ip address | grep -oP '(^[\d]+:\s)\K[\d\w]+'); do
  mac=$(ip address show ${each} | grep -oP '(?<=link/ether\s)\K[\da-f:]+|(?<=link/loopback\s)\K[\da-f:]+')
  for address in $(ip address show ${each} | grep -oP '(?<=inet\s)\K[\d.]+|(?<=inet6\s)\K[\da-f:]+'); do
    printf '%10s %32s %32s\n' ${each} ${address} ${mac}
  done
done

Output:

 interface                        ipaddress                       macaddress
----------------------------------------------------------------------------
        lo                        127.0.0.1                00:00:00:00:00:00
        lo                              ::1                00:00:00:00:00:00
      wlo1                      192.168.0.7                c8:aa:bb:cc:dd:ee
      wlo1        fe80::7aec:8287:9f45:d833                c8:aa:bb:cc:dd:ee
   docker0                       172.17.0.1                02:42:0d:0d:0d:0d
      tap0                        10.1.30.2                16:50:cc:cc:cc:cc
      tap0        fe80::10a9:d3ff:fece:57d7                16:50:cc:cc:cc:cc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM