Display ethernet interface and its corresponding IP address from Linux "ip a s" - linux

I am trying to list all the ethernet device names and its assigned IP address available in the RHEL node using the output of ip addr show command
I print all the network interfaces names only with the following:
ip a s | awk -F: '/^[^ ]/ {print $2}'
I am trying to get the output in the below format by applying more logic and coding in the above awk command (or anything preferably sed or perl possibly a one-liner):
eth0: 10.xx.xx.xx
eth1: 172.xx.xx.xx
Also, loopback lo device has to be ignored in the output as this output goes to ansible inventory file after verification

Try
ip --oneline addr show
which should be reasonably convenient to parse with Awk.
ip --oneline addr show | awk '$3 == "inet" && $2 != "lo" { print $2 ": " $4 }
Maybe see also ip --brief which is even more compact.
For more advanced usage, there is also ip --json addr show which outputs very detailed information about all interfaces in JSON format. See also the ip manual page.

Related

Command for printing IP address in Ubuntu not understood

It is the first time I use a Linux distribution and I find --help very difficult to use in order to unserstand the following command:
ifconfig eth0 | grep inet | awk '{ print $2 }'
Someone to explain to me please what the words of this command do? what is the name of | in english?
Thanks
The | sign called pipeline and it is an operator that sends the output of the command in it left side as the input of the command in it right side.
So basicly, you have 3 commands:
ifconfig eth0
which outputs many details on your network, then you send that output to:
grep inet
which takes only the lines that contain the word inet and send that to:
awk '{ print $2 }'
which print the just seconed word.

Get MAC address using shell script

Currently all the solution mentioned for getting the MAC address always use eth0.
But what if instead of eth0 my interfaces start with eth1. Also on OS X the interface names are different.
Also the interface eth0 may be present but is unused. i.e. not active, it doesn't have an IP.
So is there a way I could get the MAC address for the first available interface that is Active.(i.e. it has an inet address, I even don't want one having inet6).
For E.g
eth0 Link encap:Ethernet HWaddr <some addr>
inet6 addr: <some addr> Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:123
RX packets:123 errors:123 dropped:123 overruns:123 frame:123
TX packets:123 errors:123 dropped:123 overruns:123 carrier:123
collisions:123 txqueuelen:123
RX bytes:123 (123 MB) TX bytes:123 (123 KB)
Interrupt:123 Memory:00000000-00000000
eth1 Link encap:Ethernet HWaddr <some addr>
inet addr:<some addr> Bcast:<some addr> Mask:<some addr>
inet6 addr: <some addr> Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:123 Metric:123
RX packets:123 errors:123 dropped:123 overruns:123 frame:123
TX packets:123 errors:123 dropped:123 overruns:123 carrier:123
collisions:123 txqueuelen:123
RX bytes:123 (123 MB) TX bytes:123 (123 KB)
Interrupt:123 Memory:00000000-00000000
NOTE : I have changed the values of the output.
So in this case I want the HWaddr for eth1 and not eth0.
How do I find it ? Also it should work on all the Linux flavours.
You can do as follows
ifconfig <Interface ex:eth0,eth1> | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'
Also you can get MAC for all interface as follows
cat /sys/class/net/*/address
For particular interface like for eth0
cat /sys/class/net/eth0/address
The best Linux-specific solution is to use sysfs:
$ IFACE=eth0
$ read MAC </sys/class/net/$IFACE/address
$ echo $IFACE $MAC
eth0 00:ab:cd:12:34:56
This method is extremely clean compared to the others and spawns no additional processes since read is a builtin command for POSIX shells, including non-BASH shells. However, if you need portability to OS X, then you'll have to use ifconfig and sed methods, since OS X does not have a virtual filesystem interface like sysfs.
$ ip route show default | awk '/default/ {print $5}'
return: eth0 (my online interface)
$ cat /sys/class/net/$(ip route show default | awk '/default/ {print $5}')/address
return: ec:a8:6b:bd:55:05 (macaddress of the eth0, my online interface)
Terminal image
On a modern GNU/Linux system you can see the available network interfaces listing the content of /sys/class/net/, for example:
$ ls /sys/class/net/
enp0s25 lo virbr0 virbr0-nic wlp2s0
You can check if an interface is up looking at operstate in the device directory. For example, here's how you can see if enp0s25 is up:
$ cat /sys/class/net/enp0s25/operstate
up
You can then get the MAC address of that interface with:
$ cat /sys/class/net/enp0s25/address
ff:00:ff:e9:84:a5
For example, here's a simple bash script that prints MAC addresses for active interfaces:
#!/bin/bash
# getmacifup.sh: Print active NICs MAC addresses
D='/sys/class/net'
for nic in $( ls $D )
do
echo $nic
if grep -q up $D/$nic/operstate
then
echo -n ' '
cat $D/$nic/address
fi
done
And here's its output on a system with an ethernet and a wifi interface:
$ ./getmacifup.sh
enp0s25
ff:00:ff:e9:84:a5
lo
wlp2s0
For details see the Kernel documentation
Remember also that from 2015 most GNU/Linux distributions switched to systemd, and don't use ethX interface naming scheme any more - now they use a more robust naming convention based on the hardware topology, see:
Predictable Network Interface Names
systemd/src/udev/udev-builtin-net_id.c
Observe that the interface name and the MAC address are the first and last fields on a line with no leading whitespace.
If one of the indented lines contains inet addr: the latest interface name and MAC address should be printed.
ifconfig -a |
awk '/^[a-z]/ { iface=$1; mac=$NF; next }
/inet addr:/ { print iface, mac }'
Note that multiple interfaces could meet your criteria. Then, the script will print multiple lines. (You can add ; exit just before the final closing brace if you always only want to print the first match.)
Simply run:
ifconfig | grep ether | cut -d " " -f10
OR
ip a | grep ether | cut -d " " -f6
These two example commands will grep all lines with "ether" string and cut the mac address (that we need) following the number spaces (specified in the -f option) of the grepped portion.
Tested on different Linux flavors
I know that is a little bit dated, but with basic commands, we can take the mac address of an interface:
ip link show eth0 | grep link/ether | awk '{print $2}'
Have a nice day!
oh, if you want only the mac ether mac address, you can use that:
ifconfig | grep "ether*" | tr -d ' ' | tr -d '\t' | cut -c 6-42
(work on macintosh)
ifconfig -- get all info
grep -- keep the line with address
tr -- clean all
cut -- remove the "ether" to have only the address
None of the above worked for me because my devices are in a balance-rr bond. Querying either would say the same MAC address with ip l l, ifconfig, or /sys/class/net/${device}/address, so one of them is correct, and one is unknown.
But this works if you haven't renamed the device (any tips on what I missed?):
udevadm info -q all --path "/sys/class/net/${device}"
And this works even if you rename it (eg. ip l set name x0 dev p4p1):
cat /proc/net/bonding/bond0
or my ugly script that makes it more parsable (untested driver/os/whatever compatibility):
awk -F ': ' '
$0 == "" && interface != "" {
printf "%s %s %s\n", interface, mac, status;
interface="";
mac=""
};
$1 == "Slave Interface" {
interface=$2
};
$1 == "Permanent HW addr" {
mac=$2
};
$1 == "MII Status" {
status=$2
};
END {
printf "%s %s %s\n", interface, mac, status
}' /proc/net/bonding/bond0
This was the only thing that worked for me on Armbian:
dmesg | grep -oE 'mac=.*\w+' | cut -b '5-'
I have used command hciconfig with two greps to separate the PC Mac address and I saved the MAC address to variable:
PCMAC=$( hciconfig -a | grep -E 'BD Address:' | grep -Eo '[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}' )
You can also use this command to check if MAC address is in valid format. Note, that only big chars A-F are allowed and also you need to add input for this grep command:
grep -E '[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}'
This is my solution:
ip a | grep link/ether | awk -F " " '{print $2}'
Here's an alternative answer in case the ones listed above don't work for you. You can use the following solution(s) as well, which was found here:
ip addr
OR
ip addr show
OR
ip link
All three of these will show your MAC address(es) next to link/ether. I stumbled on this because I had just done a fresh install of Debian 9.5 from a USB stick without internet access, so I could only do a very minimal install, and received
-bash: ifconfig: command not found
when I tried some of the above solutions. I figured somebody else may come across this problem as well. Hope it helps.
Get MAC adress for eth0:
$ cat /etc/sysconfig/network-scripts/ifcfg-eth0 | grep HWADDR | cut -c 9-25
Example:
[me#machine ~]$ cat /etc/sysconfig/network-scripts/ifcfg-eth0 | grep HWADDR | cut -c 9-25
55:b5:00:10:be:10

Retrieve the name of a Network Interface using an IP Address and AWK Bash

I am trying to use Bash on CentOS 6.4 to retrieve the network interface name attached to an IP address using AWK. I have a bit of command from a Solaris box, but I'm not sure how to convert it to Linux output.
The command looks like this:
ifconfig -a | awk '
$1 ~ /:/ {split($1,nic,":");
lastif=sprintf("%s:%s",nic[1],nic[2]);}
$2 == "'$1'" { print lastif ; exit; }
'
Its part of a script, so it takes commandline argument like monitor.sh x.x.x.x y.y.y.y and it uses the first x.x.x.x to get the interface name, then makes $1 == $2 so then it can ping y.y.y.y later. I'm guessing that in Solaris the ifconfig -a output is different than CentOS. I can get the interface name if the IP and interface are on the same line, but in linux, they're on two different lines. Any ideas.
I don't have CentOS, but in RHEL, IP address is listed as inet address. I believe they should be same.
The following command should give you the interface name which has a IP address.
export iface=$(ifconfig | grep -B1 "inet addr:x.x.x.x" | awk '$1!="inet" && $1!="--" {print $1}')
echo "$iface" # To get the interface name for x.x.x.x ip
And this one should show the IP including localhost :
ifconfig | grep "inet addr:" | sed -e 's/addr:/addr: /g' | awk '{print $3}'
geting ifname for 127.0.0.1 (or any other IP)
ifconfig | awk '/127.0.0.1/ {print $1}' RS="\n\n"
lo
getting ip:
ifconfig | awk -F"[ :]+" '/inet addr:/ {print $4}'
Post the output of ifconfig, and I can help you fine tune for your OS

How to find network interface name

I have a bash script that runs on a variety of different Ubuntu Linux machines. Its job is to find out the LAN IPv4 address of the localhost.
The script is using
ip addr show eth0 | sed -n '/inet /{s/^.*inet \([0-9.]\+\).*$/\1/;p}'
which is fine, but some machines for some reason use eth1 instead of eth0. I would like to be able to discover the LAN iface name, so I can substitute it in here instead of eth0.
Of course, if you can come up with a different oneliner that does the same thing, all good.
The main NIC will usually have a default route. So:
ip -o -4 route show to default
The NIC:
ip -o -4 route show to default | awk '{print $5}'
The gateway:
ip -o -4 route show to default | awk '{print $3}'
Unlike ifconfig, ip has a consistent & parsable output. It only works on Linux; it won't work on other Unixen.
Not sure if this helps, but it seems that ip route get will show which interface it uses to connect to a remote host.
ubuntu#ip-10-40-24-21:/nail/srv/elasticsearch$ ip route get 8.8.8.8
8.8.8.8 via <gateway address> dev eth0 src <eth0 IP Address>
of course you could automate that in shell script with something like,
ip route get 8.8.8.8 | awk '{ print $NF; exit }'
Most recenttly systemd/udev has automatically started to assign interface names for all local Ethernet, WLAN and WWAN interfaces to something that we're all accustomed to . This is a departure from the traditional interface naming scheme ("eth0", "eth1", "wlan0", ...) .. now we have to check first what the local interface name is before we can use it while previously we it was a pretty accurate guess that "eth0" was the right name. What you're asking for is the network NAME .. Here's a small script to solve the problem
Use "ip route get 8.8.8.8 " to figure out which ACTIVE interface has the route to internet ( or currently being used )
Output should look like :
8.8.4.4 via 10.10.1.1 dev enp0s3 src 10.10.1.118
cache
Use awk to print the 5th text block for Interface NAME
]# ip route get 8.8.8.8 | awk -- '{print $5}'
Output : enp0s3
Use awk to print the 7th text block for Interface Address
]# ip route get 8.8.8.8 | awk -- '{print $7}'
Output : 10.10.1.118
How about searching for the string inet and brd (for broadcast)? That would give you:
ip addr show|egrep '^ *inet'|grep brd|awk -- '{ print $2; }'|sed -e 's:/[0-9]*$::'
Note that I'm using more commands than necessary; you can probably achieve the same thing with sed and a more complex regexp but I prefer a command that makes it obvious by which steps I arrive at the result.
If you want to run it in a single command, I suggest to try awk:
ip addr show|awk -- '$1 == "inet" && $3 == "brd" { split($2,a,"/"); print a[1]; }'
which isn't much longer than the sed version but more readable.
+1 Slightly more readable:
ip addr show | awk '$1 == "inet" && $3 == "brd" { sub (/\/.*/,""); print $2 }'
Believe it or not, there is no standard, easy way to get this information. There is no standard give me the current IP and Interface Name command. There isn't even a standard format for the information returned by ifconfig.
I was going to recommend forgoing pure shell and go with a scripting language like Python where you can do this:
import socket
socket.gethostbyname(socket.gethostname())
Except it doesn't work on most Linux systems because there's usually an entry in the /etc/host file pointing to 127.0.0.1, the loopback address. Perl has the same issues.
You have a firm grasp on the scripting involved, and you've seen the issues. The only thing I can recommend is to test this on each machine you're going to run it on, and see what pops out. There isn't going to be a general purpose one liner that works with all operating systems, or even with different systems on the same operating system because of the way the network is setup and the way interfaces may be named by each location.
I'd still like to know if there was an easier way to do this, but this is my workaround: I know the LAN subnet, so...
ip addr show | grep "inet 10.67.5." \
| sed -n '/inet /{s/^.*inet \([0-9.]\+\).*$/\1/;p}'
1) This one print only interface names (I needed that for handing upcoming and downcoming PPP links):
for i in $( ifconfig | grep 'ppp' | awk '{print $1}' );
do
printf "$i "; ## Or echo
done
Result:
ppp0 ppp1 ppp2
2) This one prints interface names and IP
declare -a IPADDR
index=0
for i in $( ifconfig | grep 'inet addr' | awk '{print $2}'| sed 's#addr:##g' );
do
IPADDR[$index]=$i
let "index += 1"
done
index=0
for i in $( ifconfig | grep 'ppp' | awk '{print $1}' );
do
echo $i
let "index += 1"
done
Result:
ppp0 addr:IP
ppp1 addr:IP
ppp2 addr:IP

How do I get the IP of only one Interface

When I tried ifconfig it gives me the whole all the information regarding the Network Adapter.
I tried :
system( "ifconfig -a | grep inet | "
"sed 's/\\([ ]*[^ ]*\\)\\([ ]*[^ ]*\\).*$/\\1 \\2/' "
" > address.txt" ) ;
which output two Ips :
inet addr:17.24.17.229
inet addr:127.0.0.1
But I need just the 1st one , How can I filter this out.
You might use head but...
I might be mistaking of course, but my guess is that you don't really need the first one.
You're probably looking for the one that is connected to the gateway (or the Internet).
As far as I know, the order of the IP addresses or interfaces is unspecified.
What do you want to achieve exactly ?
If you want to know what interface is "connected to the internet", a more reliable approach is to find the interface which has the default route (using route) then to use ifconfig <interface> to directly get the correct IP address.
you can reduce the use of grep and head
ifconfig -a | sed -nr -e '/inet\b/{s|^.*inet\s+addr:(.[^ \t]*).*|\1|;h}' -e '${x;p}'
I'd use iproute2's ip:
ip -o addr show dev eth0 | while read IFNUM IFNAME ADDRTYPE ADDR REST; do [ "$ADDRTYPE" == "inet" ] && echo $ADDR; done
9.87.65.43/21
(Not only because it's easier to parse, but it'll also show e.g. secondary IPs, which ifconfig can't.)
Don't look at all of the adapters, just the one you want.
system( "ifconfig -a eth0 | grep inet | "
"sed 's/\\([ ]*[^ ]*\\)\\([ ]*[^ ]*\\).*$/\\1 \\2/' "
" > address.txt" ) ;
If the output of ifconfig or ip ever changes, your program will break.
Why not not just use the SIOCGIFCONF ioctl() and get it directly from the source?
ETA: It's also unsafe to assume that any given system will have just one loopback interface and just one Ethernet with a single address.
How about 'ifconfig eth0'?
hostname -I | awk '{print $1}'

Resources