Sorting information and processing output with variables in Bash - bash

I've received some helpful responses in the past and am hoping you can all help me out. I came across some weird behavior that I can't quite nail down. I'm processing configuration files for Cisco switches and want to generate output that lists the VLAN IP Addresses in a format that would show:
Vlan1: 172.31.200.1 255.255.255.0
Vlan10: 172.40.220.1 255.255.255.0
The "Vlan" would be captured in a variable and the IP/Mask is extracted using "sed" and it works for the most part. Occasionally though it refuses to populate the "vlan" variable even though it appears to work great for other configs.
If there's only one VLAN it just handles that one, if there's more than one it handles the additional ones. If the user selects (-v) it includes VLAN1 on the list there are multiple VLANs configured (otherwise it ignores VLAN1).
This input file appears broken (Filename 1.cfg):
!
interface Vlan1
ip address 172.29.96.100 255.255.255.0
!
ip default-gateway 172.29.96.1
ip http server
no ip http secure-server
!
This input file works fine (Filename 2.cfg):
!
interface Vlan1
ip address 172.31.200.111 255.255.255.0
no ip route-cache
!
ip default-gateway 172.31.200.1
ip http server
ip http secure-server
The output that I get is this:
Notice how the first one fails to include the "Vlan1" reference?
Here's my script:
#!/bin/bash
if [ -f getlan.log ];
then
rm getlan.log
fi
TempFile=getlan.log
verbose=0
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
-v)
verbose=1
shift
;;
#*)
#exit
#shift
#;;
esac
done
#Start Processing all files
files=$( ls net )
for i in $files; do
#########################################################
# Collect Configured VLAN Interfaces and IP Information #
#########################################################
echo "-------- Configured VLAN Interfaces --------" >> ~/$TempFile
echo "" >> ~/$TempFile
if [ `grep "^interface Vlan" ~/net/$i | awk '{ print $2 }' | wc -l` -gt 1 ];
then
for g in `grep "^interface Vlan" ~/net/$i | awk '{ print $2 }'`;
do
if [ $g == "Vlan1" ];
then
if [ $verbose -gt 0 ];
then
echo "$g": `sed -n '/^interface '$g'/,/!/p' ~/net/$i | head -n 5 | grep -i "ip address" | awk '{ print $3, $4 }'` >> ~/$TempFile
fi
else
echo "$g": `sed -n '/^interface '$g'/,/^!/p' ~/net/$i | grep -i "ip address" | awk '{ print $3, $4 }'` >> ~/$TempFile
fi
done
echo "" >> ~/$TempFile
else
vlanid=`grep "^interface Vlan" ~/net/$i | awk '{ print $2 }'`
echo $vlanid: `sed -n '/^interface 'Vlan'/,/^!/p' ~/net/$i | grep -i "address" | awk '{ print $3, $4 }'` >> ~/$TempFile
echo "" >> ~/$TempFile
fi
done
It would be really great if this was more consistent. Thanks!

A best-practices approach might look more like:
#!/usr/bin/env bash
interface_re='^[[:space:]]*interface[[:space:]]+(.*)'
ip_re='^[[:space:]]*ip address (.*)'
process_file() {
local line interface
interface=
while IFS= read -r line; do
if [[ $line =~ $interface_re ]]; then
interface=${BASH_REMATCH[1]}
continue
fi
if [[ $interface ]] && [[ $line =~ $ip_re ]]; then
echo "${interface}: ${BASH_REMATCH[1]}"
fi
done
}
for file in net/*; do
process_file <"$file"
done
This can be tested as follows:
process_file <<'EOF'
!
interface Vlan1
ip address 172.29.96.100 255.255.255.0
!
ip default-gateway 172.29.96.1
ip http server
no ip http secure-server
!
!
interface Vlan1
ip address 172.31.200.111 255.255.255.0
no ip route-cache
!
ip default-gateway 172.31.200.1
ip http server
ip http secure-server
EOF
...which correctly identifies the ip address lines from both interface blocks, emitting:
Vlan1: 172.29.96.100 255.255.255.0
Vlan1: 172.31.200.111 255.255.255.0

Related

I am not able to Ping IPs from my indexed array but works with an associative array

I am trying to iterate IPs which are read from a csv to an array as a kind of monitoring solution. I have the ips in a indexed array and want to pass the ips to the ping command but its not working.
#!/bin/bash
datei=hosts.csv
length=$(cat $datei | wc -l)
for (( i=1; i<=$length; i++ ))
do
ips[$i]=$(cut -d ';' -f2 $datei | awk 'NR=='$i'')
hosts[$i]=$(cut -d ';' -f1 $datei | awk 'NR=='$i'')
done
servers=( "1.1.1.1" "8.8.4.4" "8.8.8.8" "4.4.4.4")
for i in ${ips[#]} #Here i change the array i want to iterate
do
echo $i
ping -c 1 $i > /dev/null
if [ $? -ne 0 ]; then
echo "Server down"
else
echo "Server alive"
fi
done
Interesting is that if I iterate the server array instead of the ips array it works. The ips array seems from data fine if printed.
The output if I use the servers array:
1.1.1.1
Server alive
8.8.4.4
Server alive
8.8.8.8
Server alive
4.4.4.4
Server down
and if I use the ips array
1.1.1.1
: Name or service not known
Server down
8.8.4.4
: Name or service not known
Server down
8.8.8.8
: Name or service not known
Server down
4.4.4.4
: Name or service not known
Server down
Output from cat hosts.csv
test;1.1.1.1
test;8.8.4.4
test;8.8.8.8
test;4.4.4.4
First column is for Hostnames and the second column for the IPs in v4.
I am on Ubuntu 20.4.1 LTS
Fixed multiple issues with your code:
Reading of hosts.csv into arrays.
Testing the ping result.
hosts.csv:
one.one.one.one;1.1.1.1
dns.google;8.8.4.4
dns.google;8.8.8.8
invalid.invalid;4.4.4.4
Working commented in code:
#!/usr/bin/env bash
datei=hosts.csv
# Initialize empty arrays
hosts=()
ips=()
# Iterate reading host and ip in line records using ; as field delimiter
while IFS=\; read -r host ip _; do
hosts+=("$host") # Add to the hosts array
ips+=("$ip") # Add to the ips array
done <"$datei" # From this file
# Iterate the index of the ips array
for i in "${!ips[#]}"; do
# Display currently processed host and ip
printf 'Pinging host %s with IP %s\n' "${hosts[i]}" "${ips[i]}"
# Test the result of pinging the IP address
if ping -nc 1 "${ips[i]}" >/dev/null 2>&1; then
echo "Server alive"
else
echo "Server down"
fi
done
You can read into an array from stdin using readarray and so combining this with awk to parse the Host.csv file:
readarray -t ips <<< "$(awk -F\; '{ print $2 }' $date1)"
readarray -t hosts <<< "$(awk -F\; '{ print $1 }' $date1)"

Bash script match ipv4 addresses with regex variable

Trying to get only the lines with ipv4 addresses in the $networks variable.
#!/bin/bash
ivp4_pattern='/^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))?$/igm'
networks=$(ip addr | grep "inet" | awk '{print $2}')
while read -r line;
do
echo "$line"
done <<< "$networks"
echo "$ivp4_pattern"
echo "$networks" | grep "$ivp4_pattern"
Output:
[jonathan#localhost ~]$ ./script.sh
127.0.0.1/8
::1/128
172.16.155.128/24
fe80::da84:977a:d654:7716/64
/^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))?$/igm
Tried removing the / and with -E...
#!/bin/bash
ivp4_pattern="'^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))?$'"
networks=$(ip addr | grep "inet" | awk '{print $2}')
while read -r line;
do
echo "$line"
done <<< "$networks"
echo $ivp4_pattern
echo $networks | grep -E $ivp4_pattern
Also tried loop through networks line by line and taking the regex out of the variable...
#!/bin/bash
networks=$(ip addr | grep "inet" | awk '{print $2}')
while read -r line;
do
echo "$line"
done <<< "$networks"
while read -r line;
do
echo $line
echo $line | grep '^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))?$'
done <<< "$networks"
I got it working adding -E to grep without regex in variable...but why is it working? It doesn't like the regex being in a variable?
#!/bin/bash
networks=$(ip addr | grep "inet" | awk '{print $2}')
while read -r line;
do
echo "$line"
done <<< "$networks"
while read -r line;
do
# echo $line
echo $line | grep -E '^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))?$'
done <<< "$networks"
~
As a bash solution, how about:
ipv4_pattern="([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})"
ip addr | while read -r line; do
if [[ $line =~ inet\ $ipv4_pattern ]]; then
echo "${BASH_REMATCH[1]}"
fi
done
Note that the while loop above is invoked in the child process and
variables assigned here are inaccessible from the parent.
In such a case, please make use of a process substitution as;
ipv4_pattern="([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})"
while read -r line; do
if [[ $line =~ inet\ $ipv4_pattern ]]; then
echo "${BASH_REMATCH[1]}"
# do some assignments here as ip_list+=("${BASH_REMATCH[1]}")
fi
done < <(ip addr)
Hope this helps.
If you want to list only IPv4 addresses, how about this?
The first ...
#!/bin/bash
#
# ip addr : list IP info.
# grep "inet " : Only for IPv4. IPv6 addresses are listed up with "inet6".
# awk '{print $2}': Extract IPv4 adress
ipaddrs=$(ip addr | grep "inet " | awk '{print $2}')
while read -r ipaddr
do
echo $(cut -d"/" -f1 <<< ${ipaddr})
done <<< "${ipaddrs}"
exit 0
The Second is ...
#!/bin/bash
#
# ip addr : list IP info.
# grep "inet " : Only for IPv4. IPv6 addresses are listed up with "inet6".
ipaddrs=$(ip addr | grep "inet ")
while read -r ipaddr
do
# sample: inet 100.52.62.173/24 brd 100.52.62.255 scope global bond1
ipv4_cidr=$(cut -d" " -f2 <<< ${ipaddr})
ipv4=$(cut -d"/" -f1 <<< ${ipv4_cidr})
netmask=$(cut -d"/" -f2 <<< ${ipv4_cidr})
brdcast=$(cut -d" " -f4 <<< ${ipaddr})
echo "----------------------------"
echo "============================"
echo "ip addr : ${ipaddr}"
echo "----------------------------"
echo "IP Address: ${ipv4}"
echo "Netmask : ${netmask}"
echo "Broadcast : ${brdcast}"
done <<< "${ipaddrs}"
exit 0
The third is ...
#!/bin/bash
#
# ip addr : list IP info.
# grep "inet " : Only for IPv4. IPv6 addresses are listed up with "inet6".
ipaddrs=$(ip addr | grep "inet ")
while IFS=" " read -ra ipaddr
do
# If a first line is "inet 100.52.62.173/24 brd 100.52.62.255 scope global bond1"
# 1. ipadddr is (inet 100.52.62.173/24 brd 100.52.62.255 scope global bond1)
# A second is cidr.
IFS="/" read -ra ipv4_cidr <<< "${ipaddr[1]}"
# 2. ipv4_cidr is ("100.52.62.173" "24")
ipv4="${ipv4_cidr[0]}"
netmask="${ipv4_cidr[1]}"
# A fourth is 'broadcast'.
brdcast="${ipaddr[3]}"
echo "----------------------------"
echo "============================"
echo "ip addr : ${ipaddr[#]}"
echo "----------------------------"
echo "IP Address: ${ipv4}"
echo "Netmask : ${netmask}"
echo "Broadcast : ${brdcast}"
done <<< "${ipaddrs}"
exit 0

Ping Script with filter

I have a text file with host names and IP addresses like so (one IP and one host name per row). The IP addresses and host names can be separated by a spaces and/or a pipe, and the host name may be before or after the IP address
10.10.10.10 HW-DL11_C023
11.11.11.11 HW-DL11_C024
10.10.10.13 | HW-DL12_C023
11.11.11.12 | HW-DL12_C024
HW-DL13_C023 11.10.10.10
HW-DL13_C024 21.11.11.11
HW-DL14_C023 | 11.10.10.10
HW-DL14_C024 | 21.11.11.11
The script below should be able to ping hosts with a common denominator e.g. DL13 (there are two devices and it will ping only those two). What am I doing wrong, as I simply can`t make it work?
The script is in the same directory as the data; I don`t get errors, and everything is formatted. The server is Linux.
pingme () {
hostfile="/home/rex/u128789/hostfile.txt"
IFS= mapfile -t hosts < <(cat $hostfile)
for host in "${hosts[#]}"; do
match=$(echo "$host" | grep -o "\-$1_" | sed 's/-//' | sed 's/_//')
if [[ "$match" = "$1" ]]; then
hostname=$(echo "$host" | awk '{print $2}')
ping -c1 -W1 $(echo "$host" | awk '{print $1}') > /dev/null
if [[ $? = 0 ]]; then
echo "$hostname is alive"
elif [[ $? = 1 ]]; then
echo "$hostname is dead"
fi
fi
done
}
Try adding these two lines to your code:
pingme () {
hostfile="/home/rex/u128789/hostfile.txt"
IFS= mapfile -t hosts < <(cat $hostfile)
for host in "${hosts[#]}"; do
echo "Hostname: $host" # <-------- ADD THIS LINE -------
match=$(echo "$host" | grep -o "\-$1_" | sed 's/-//' | sed 's/_//')
echo "...matched with $match" # <-------- ADD THIS LINE -------
if [[ "$match" = "$1" ]]; then
hostname=$(echo "$host" | awk '{print $2}')
ping -c1 -W1 $(echo "$host" | awk '{print $1}') > /dev/null
if [[ $? = 0 ]]; then
echo "$hostname is alive"
elif [[ $? = 1 ]]; then
echo "$hostname is dead"
fi
fi
done
}
Then when you run it, you should see a list of your hosts, at least.
If you don't then you're not reading your file successfully.
If you do, there's a problem in your per-host logic.
Congratulations! You've divided your problem into two smaller problems. Once you know which half has the problem, keep dividing the problem in half until the smallest possible problem is staring you in the face. You'll probably know the solution at that point. If not, add your findings to the question and we'll help out from there.
The original code doesn't handle the pipe separator or the possibly reversed hostname and IP address in the input file. It also makes a lot of unnecessary use of external programs (grep, sed, ...).
Try this:
# Enable extended glob patterns - e.g. +(pattern-list)
shopt -s extglob
function pingme
{
local -r host_denom=$1
local -r hostfile=$HOME/u128789/hostfile.txt
local ipaddr host tmp
# (Add '|' to the usual characters in IFS)
while IFS=$'| \t\n' read -r ipaddr host ; do
# Swap host and IP address if necessary
if [[ $host == +([0-9]).+([0-9]).+([0-9]).+([0-9]) ]] ; then
tmp=$host
host=$ipaddr
ipaddr=$tmp
fi
# Ping the host if its name contains the "denominator"
if [[ $host == *-"$host_denom"_* ]] ; then
if ping -c1 -W1 -- "$ipaddr" >/dev/null ; then
printf '%s is alive\n' "$host"
else
printf '%s is dead\n' "$host"
fi
fi
done < "$hostfile"
return 0
}
pingme DL13
The final line (call the pingme function) is just an example, but it's essential to make the code do something.
REX, you need to be more specific about your what IP's you are trying to get from this example. You also don't ping enough times IMO and your script is case sensitive checking the string (not major). Anyway,
First, check that your input and output is working correctly, in this example I'm just reading and printing, if this doesn't work fix permissions etc :
file="/tmp/hostfile.txt"
while IFS= read -r line ;do
echo $line
done < "${file}"
Next, instead of a function first try to make it work as a script, in this example I manually set "match" to DL13, then I read each line (like before) and (1) match on $match, if found I remove the '|', and then read the line into an array of 2. if the first array item is an a IP (contains periods) set it as the IP the other as hostname, else set the opposite. Then run the ping test.
# BASH4+ Example:
file="/tmp/hostfile.txt"
match="dl13"
while IFS= read -r line ;do
# -- check for matching string (e.g. dl13 --
[[ "${line,,}" =~ "${match,,}" ]] || continue
# -- We found a match, split out host/ip into vars --
line=$(echo ${line//|})
IFS=' ' read -r -a items <<< "$line"
if [[ "${items[0]}" =~ '.' ]] ;then
host="${items[1]}" ; ip="${items[0]}"
else
host="${items[0]}" ; ip="${items[1]}"
fi
# -- Ping test --
ping -q -c3 "${ip}" > /dev/null
if [ $? -eq 0 ] ;then
echo "$host is alive!"
else
echo "$host is toast!"
fi
done < "${file}"

Email Alerts when service or server automatically comes up

I am working on a bash script that helps to ping and get the network interface level status of the host machines and services.
This script will send a email alerts in case of failure.
#!/bin/bash
HOSTS="192.168.8.200"
COUNT=4
for myHost in $HOSTS
do
count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
if [ $count -eq 0 ]; then
# 100% failed
echo -e "HOST:$myHost is down (ping failed) at $(date)" | mailx -A gmail -s “Mail subject” anymail#anydomain.com
fi
done
This works fine.
But need help to get a one single email alert when host automatically comes up (ping success).
You need to save the state of the host (up/down) during the calls of your script.
if the host is "up" and the former state was "down" then you need to send an email.
You can just write the result of the "check command" to a file in /tmp/
if the check returns that the server is up you read the content of the file. if the state is "down" in the file, then send an email an write "up" to the file.
on the next check if the server is up, there will be no additional email sent, because the server was also "up" before.
#!/bin/bash
HOSTS="192.168.8.200 192.168.8.201 192.168.122.1"
COUNT=4
STATE="/tmp/ping_state.txt"
for myHost in $HOSTS
do
count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
if [ $count -eq 0 ]; then
# 100% failed
#echo -e "HOST:$myHost is down (ping failed) at $(date)" | mailx -A gmail -s “Mail subject” anymail#anydomain.com
echo "host $myHost down"
#delete all previous entries of that ip
sed -i "/$myHost/d" $STATE
#mark host as down
echo "$myHost - down" >> $STATE
else
CHECK=`grep "$myHost" $STATE | grep -o "down"`
if [ "$CHECK" = "down" ]; then
echo "host $myHost up again"
#insert email for host up here
fi
#delete all previous entries of that ip
sed -i "/$myHost/d" $STATE
echo "$myHost - up" >> $STATE
fi
done
for simple testing I just used an echo statement instead of sending an email.

How to get the primary IP address of the local machine on Linux and OS X? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 4 years ago.
Improve this question
I am looking for a command line solution that would return me the primary (first) IP address of the localhost, other than 127.0.0.1
The solution should work at least for Linux (Debian and RedHat) and OS X 10.7+
I am aware that ifconfig is available on both but its output is not so consistent between these platforms.
Use grep to filter IP address from ifconfig:
ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'
Or with sed:
ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p'
If you are only interested in certain interfaces, wlan0, eth0, etc. then:
ifconfig wlan0 | ...
You can alias the command in your .bashrc to create your own command called myip for instance.
alias myip="ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p'"
A much simpler way is hostname -I (hostname -i for older versions of hostname but see comments). However, this is on Linux only.
The following will work on Linux but not OSX.
This doesn't rely on DNS at all, and it works even if /etc/hosts is not set correctly (1 is shorthand for 1.0.0.0):
ip route get 1 | awk '{print $NF;exit}'
or avoiding awk and using Google's public DNS at 8.8.8.8 for obviousness:
ip route get 8.8.8.8 | head -1 | cut -d' ' -f8
A less reliable way: (see comment below)
hostname -I | cut -d' ' -f1
For linux machines (not OS X) :
hostname --ip-address
Solution
$ ip -o route get to 8.8.8.8 | sed -n 's/.*src \([0-9.]\+\).*/\1/p'
192.168.8.16
Explanation
The correct way to query network information is using ip:
-o one-line output
route get to get the actual kernel route to a destination
8.8.8.8 Google IP, but can use the real IP you want to reach
e.g. ip output:
8.8.8.8 via 192.168.8.254 dev enp0s25 src 192.168.8.16 uid 1000 \ cache
To extract the src ip, sed is the ligthest and most compatible with regex support:
-n no output by default
's/pattern/replacement/p' match pattern and print replacement only
.*src \([0-9.]\+\).* match the src IP used by the kernel, to reach 8.8.8.8
e.g. final output:
192.168.8.16
Other answers
I think none of the preceding answer are good enough for me, as they don't work in a recent machine (Gentoo 2018).
Issues I found with preceding answers:
use of positional column in command output;
use of ifconfig which is deprecated and -- for example -- don't list multple IPs;
use of awk for a simple task which sed can handle better;
ip route get 1 is unclear, and is actually an alias for ip route get to 1.0.0.0
use of hostname command, which don't have -I option in all appliance and which return 127.0.0.1 in my case.
on Linux
hostname -I
on macOS
ipconfig getifaddr en0
hostname -I can return multiple addresses in an unreliable order (see the hostname manpage), but for me it just returns 192.168.1.X, which is what you wanted.
Edited (2014-06-01 2018-01-09 2021-07-25)
From some time ago, I use now newer ip tool. But under bash, I will do simply:
read -r _{,} gateway _ iface _ ip _ < <(ip r g 1.0.0.0)
Then
printf '%-12s %s\n' gateway $gateway iface $iface ip $ip
gateway 192.168.1.1
iface eth0
ip 192.168.1.37
From there, the mask is:
while IFS=$' /\t\r\n' read lne lip lmask _;do
[ "$lne" = "inet" ] && [ "$lip" = "$ip" ] && mask=$lmask
done < <(ip a s dev $iface)
echo Mask is $mask bits.
Mask is 24 bits.
Then if you want to see your mask as an IP:
printf -v msk '%*s' $mask ''
printf -v msk %-32s ${msk// /1}
echo $((msk=2#${msk// /0},msk>>24)).$((msk>>16&255)).$((msk>>8&255)).$((msk&255))
255.255.255.0
Edited (2014-06-01 2018-01-09)
For stronger config, with many interfaces and many IP configured on each interfaces, I wrote a pure bash script (not based on 127.0.0.1) for finding correct interface and ip, based on default route. I post this script at very bottom of this answer.
Intro
As both Os have bash installed by default, there is a bash tip for both Mac and Linux:
The locale issue is prevented by the use of LANG=C:
myip=
while IFS=$': \t' read -a line ;do
[ -z "${line%inet}" ] && ip=${line[${#line[1]}>4?1:2]} &&
[ "${ip#127.0.0.1}" ] && myip=$ip
done< <(LANG=C /sbin/ifconfig)
echo $myip
Putting this into a function:
Minimal:
getMyIP() {
local _ip _line
while IFS=$': \t' read -a _line ;do
[ -z "${_line%inet}" ] &&
_ip=${_line[${#_line[1]}>4?1:2]} &&
[ "${_ip#127.0.0.1}" ] && echo $_ip && return 0
done< <(LANG=C /sbin/ifconfig)
}
Simple use:
getMyIP
192.168.1.37
Fancy tidy:
getMyIP() {
local _ip _myip _line _nl=$'\n'
while IFS=$': \t' read -a _line ;do
[ -z "${_line%inet}" ] &&
_ip=${_line[${#_line[1]}>4?1:2]} &&
[ "${_ip#127.0.0.1}" ] && _myip=$_ip
done< <(LANG=C /sbin/ifconfig)
printf ${1+-v} $1 "%s${_nl:0:$[${#1}>0?0:1]}" $_myip
}
Usage:
getMyIP
192.168.1.37
or, running same function, but with an argument:
getMyIP varHostIP
echo $varHostIP
192.168.1.37
set | grep ^varHostIP
varHostIP=192.168.1.37
Nota: Without argument, this function output on STDOUT, the IP and a newline, with an argument, nothing is printed, but a variable named as argument is created and contain IP without newline.
Nota2: This was tested on Debian, LaCie hacked nas and MaxOs. If this won't work under your environ, I will be very interested by feed-backs!
Older version of this answer
( Not deleted because based on sed, not bash. )
Warn: There is an issue about locales!
Quick and small:
myIP=$(ip a s|sed -ne '/127.0.0.1/!{s/^[ \t]*inet[ \t]*\([0-9.]\+\)\/.*$/\1/p}')
Exploded (work too;)
myIP=$(
ip a s |
sed -ne '
/127.0.0.1/!{
s/^[ \t]*inet[ \t]*\([0-9.]\+\)\/.*$/\1/p
}
'
)
Edit:
How! This seem not work on Mac OS...
Ok, this seem work quite same on Mac OS as on my Linux:
myIP=$(LANG=C /sbin/ifconfig | sed -ne $'/127.0.0.1/ ! { s/^[ \t]*inet[ \t]\\{1,99\\}\\(addr:\\)\\{0,1\\}\\([0-9.]*\\)[ \t\/].*$/\\2/p; }')
splitted:
myIP=$(
LANG=C /sbin/ifconfig |
sed -ne $'/127.0.0.1/ ! {
s/^[ \t]*inet[ \t]\\{1,99\\}\\(addr:\\)\\{0,1\\}\\([0-9.]*\\)[ \t\/].*$/\\2/p;
}')
My script (jan 2018):
This script will first find your default route and interface used for, then search for local ip matching network of gateway and populate variables. The last two lines just print, something like:
Interface : en0
Local Ip : 10.2.5.3
Gateway : 10.2.4.204
Net mask : 255.255.252.0
Run on mac : true
or
Interface : eth2
Local Ip : 192.168.1.31
Gateway : 192.168.1.1
Net mask : 255.255.255.0
Run on mac : false
Well, there it is:
#!/bin/bash
runOnMac=false
int2ip() { printf ${2+-v} $2 "%d.%d.%d.%d" \
$(($1>>24)) $(($1>>16&255)) $(($1>>8&255)) $(($1&255)) ;}
ip2int() { local _a=(${1//./ }) ; printf ${2+-v} $2 "%u" $(( _a<<24 |
${_a[1]} << 16 | ${_a[2]} << 8 | ${_a[3]} )) ;}
while IFS=$' :\t\r\n' read a b c d; do
[ "$a" = "usage" ] && [ "$b" = "route" ] && runOnMac=true
if $runOnMac ;then
case $a in
gateway ) gWay=$b ;;
interface ) iFace=$b ;;
esac
else
[ "$a" = "0.0.0.0" ] && [ "$c" = "$a" ] && iFace=${d##* } gWay=$b
fi
done < <(/sbin/route -n 2>&1 || /sbin/route -n get 0.0.0.0/0)
ip2int $gWay gw
while read lhs rhs; do
[ "$lhs" ] && {
[ -z "${lhs#*:}" ] && iface=${lhs%:}
[ "$lhs" = "inet" ] && [ "$iface" = "$iFace" ] && {
mask=${rhs#*netmask }
mask=${mask%% *}
[ "$mask" ] && [ -z "${mask%0x*}" ] &&
printf -v mask %u $mask ||
ip2int $mask mask
ip2int ${rhs%% *} ip
(( ( ip & mask ) == ( gw & mask ) )) &&
int2ip $ip myIp && int2ip $mask netMask
}
}
done < <(/sbin/ifconfig)
printf "%-12s: %s\n" Interface $iFace Local\ Ip $myIp \
Gateway $gWay Net\ mask $netMask Run\ on\ mac $runOnMac
Specific to only certain builds of Ubuntu. Though it may just tell you 127.0.0.1:
hostname -i
or
hostname -I
You can also get IP version 4 address of eth0 by using this command in linux
/sbin/ip -4 -o addr show dev eth0| awk '{split($4,a,"/");print a[1]}'
Output will be like this
[root#localhost Sathish]# /sbin/ip -4 -o addr show dev eth0| awk '{split($4,a,"/");print a[1]}'
192.168.1.22
This works on Linux and OSX
This will get the interface associated to the default route
NET_IF=`netstat -rn | awk '/^0.0.0.0/ {thif=substr($0,74,10); print thif;} /^default.*UG/ {thif=substr($0,65,10); print thif;}'`
Using the interface discovered above, get the ip address.
NET_IP=`ifconfig ${NET_IF} | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'`
OSX
uname -a
Darwin laptop 14.4.0 Darwin Kernel Version 14.4.0: Thu May 28 11:35:04 PDT 2015; root:xnu-2782.30.5~1/RELEASE_X86_64 x86_64
echo $NET_IF
en5
echo $NET_IP
192.168.0.130
CentOS Linux
uname -a
Linux dev-cil.medfx.local 2.6.18-164.el5xen 1 SMP Thu Sep 3 04:03:03 EDT 2009 x86_64 x86_64 x86_64 GNU/Linux
echo $NET_IF
eth0
echo $NET_IP
192.168.46.10
Using some of the other methods You may enter a conflict where multiple IP adresses is defined on the system.
This line always gets the IP address by default used.
ip route get 8.8.8.8 | head -1 | awk '{print $7}'
ifconfig | grep 'inet ' | grep -v '127.0.0.1' | awk '{print $2}'
Im extracting my comment to this answer:
ip route get 1 | sed -n 's/^.*src \([0-9.]*\) .*$/\1/p'
It bases on #CollinAnderson answer which didn't work in my case.
Assuming you need your primary public IP as it seen from the rest of the world, try any of those:
wget http://ipecho.net/plain -O - -q
curl http://icanhazip.com
curl http://ifconfig.me/ip
Finds an IP address of this computer in a network which is a default gateway (for example excludes all virtual networks, docker bridges) eg. internet gateway, wifi gateway, ethernet
ip route| grep $(ip route |grep default | awk '{ print $5 }') | grep -v "default" | awk '/scope/ { print $9 }'
Works on Linux.
Test:
➜ ~ ip route| grep $(ip route |grep default | awk '{ print $5 }') | grep -v "default" | awk '/scope/ { print $9 }'
192.168.0.114
➜ reverse-networking git:(feature/type-local) ✗ ifconfig wlp2s0
wlp2s0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.0.114 netmask 255.255.255.0 broadcast 192.168.0.255
inet6 fe80::d3b9:8e6e:caee:444 prefixlen 64 scopeid 0x20<link>
ether ac:x:y:z txqueuelen 1000 (Ethernet)
RX packets 25883684 bytes 27620415278 (25.7 GiB)
RX errors 0 dropped 27 overruns 0 frame 0
TX packets 7511319 bytes 1077539831 (1.0 GiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
The shortest way to get your local ipv4-address on your linux system:
hostname -I | awk '{print $1}'
I have to add to Collin Andersons answer that this method also takes into account if you have two interfaces and they're both showing as up.
ip route get 1 | awk '{print $NF;exit}'
I have been working on an application with Raspberry Pi's and needed the IP address that was actually being used not just whether it was up or not. Most of the other answers will return both IP address which isn't necessarily helpful - for my scenario anyway.
Primary network interface IP
ifconfig `ip route | grep default | head -1 | sed 's/\(.*dev \)\([a-z0-9]*\)\(.*\)/\2/g'` | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" | head -1
ip addr show | grep -E '^\s*inet' | grep -m1 global | awk '{ print $2 }' | sed 's|/.*||'
Another ifconfig variantion that works both on Linux and OSX:
ifconfig | grep "inet " | cut -f2 -d' '
Not sure if this works in all os, try it out.
ifconfig | awk -F"[ :]+" '/inet addr/ && !/127.0/ {print $4}'
I went through a lot of links (StackExchange, AskUbuntu, StackOverflow etc) and came to the decision to combine all the best solutions into one shell script.
In my opinion these two QAs are the best of seen:
How can I get my external IP address in a shell script?
https://unix.stackexchange.com/q/22615
How do I find my internal ip address?
https://askubuntu.com/a/604691
Here is my solution based on some ideas by rsp shared in his repository (https://github.com/rsp/scripts/).
Some of you could say that this script is extremely huge for so simple task but I'd like to make it easy and flexible in usage as much as possible. It supports simple configuration file allowing redefine the default values.
It was successfully tested under Cygwin, MINGW and Linux (Red Hat).
Show internal IP address
myip -i
Show external IP address
myip -e
Source code, also available by the link: https://github.com/ildar-shaimordanov/tea-set/blob/master/home/bin/myip. Example of configuration file is there, next to the main script.
#!/bin/bash
# =========================================================================
#
# Getting both internal and external IP addresses used for outgoing
# Internet connections.
#
# Internal IP address is the IP address of your computer network interface
# that would be used to connect to Internet.
#
# External IP address is the IP address that is visible by external
# servers that you connect to over Internet.
#
# Copyright (C) 2016 Ildar Shaimordanov
#
# =========================================================================
# Details of the actual implementation are based on the following QA:
#
# How can I get my external IP address in a shell script?
# https://unix.stackexchange.com/q/22615
#
# How do I find my internal ip address?
# https://askubuntu.com/a/604691
# =========================================================================
for f in \
"$( dirname "$0" )/myip.conf" \
~/.myip.conf \
/etc/myip.conf
do
[ -f "$f" ] && {
. "$f"
break
}
done
# =========================================================================
show_usage() {
cat - <<HELP
USAGE
$( basename "$0" ) [OPTIONS]
DESCRIPTION
Display the internal and external IP addresses
OPTIONS
-i Display the internal IP address
-e Display the external IP address
-v Turn on verbosity
-h Print this help and exit
HELP
exit
}
die() {
echo "$( basename "$0" ): $#" >&2
exit 2
}
# =========================================================================
show_internal=""
show_external=""
show_verbose=""
while getopts ":ievh" opt
do
case "$opt" in
i )
show_internal=1
;;
e )
show_external=1
;;
v )
show_verbose=1
;;
h )
show_usage
;;
\? )
die "Illegal option: $OPTARG"
;;
esac
done
if [ -z "$show_internal" -a -z "$show_external" ]
then
show_internal=1
show_external=1
fi
# =========================================================================
# Use Google's public DNS to resolve the internal IP address
[ -n "$TARGETADDR" ] || TARGETADDR="8.8.8.8"
# Query the specific URL to resolve the external IP address
[ -n "$IPURL" ] || IPURL="ipecho.net/plain"
# Define explicitly $IPCMD to gather $IPURL using another tool
[ -n "$IPCMD" ] || {
if which curl >/dev/null 2>&1
then
IPCMD="curl -s"
elif which wget >/dev/null 2>&1
then
IPCMD="wget -qO -"
else
die "Neither curl nor wget installed"
fi
}
# =========================================================================
resolveip() {
{
gethostip -d "$1" && return
getent ahostsv4 "$1" \
| grep RAW \
| awk '{ print $1; exit }'
} 2>/dev/null
}
internalip() {
[ -n "$show_verbose" ] && printf "Internal: "
case "$( uname | tr '[:upper:]' '[:lower:]' )" in
cygwin* | mingw* | msys* )
netstat -rn \
| grep -w '0.0.0.0' \
| awk '{ print $4 }'
return
;;
esac
local t="$( resolveip "$TARGETADDR" )"
[ -n "$t" ] || die "Cannot resolve $TARGETADDR"
ip route get "$t" \
| awk '{ print $NF; exit }'
}
externalip() {
[ -n "$show_verbose" ] && printf "External: "
eval $IPCMD "$IPURL" $IPOPEN
}
# =========================================================================
[ -n "$show_internal" ] && internalip
[ -n "$show_external" ] && externalip
# =========================================================================
# EOF
I just utilize Network Interface Names, my custom command is
[[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's#.*inet (.*)/.*brd.*#\1#p' || ip addr show dev eth0 | sed -n -r 's#.*inet (.*)/.*brd.*#\1#p'
in my own notebook
[flying#lempstacker ~]$ cat /etc/redhat-release
CentOS Linux release 7.2.1511 (Core)
[flying#lempstacker ~]$ [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's#.*inet (.*)/.*brd.*#\1#p' || ip addr show dev eth0 | sed -n -r 's#.*inet (.*)/.*brd.*#\1#p'
192.168.2.221
[flying#lempstacker ~]$
but if the network interface owns at least one ip, then it will show all ip belong to it
for example
Ubuntu 16.10
root#yakkety:~# sed -r -n 's#"##g;s#^VERSION=(.*)#\1#p' /etc/os-release
16.04.1 LTS (Xenial Xerus)
root#yakkety:~# [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's#.*inet (.*)/.*brd.*#\1#p' || ip addr show dev eth0 | sed -n -r 's#.*inet (.*)/.*brd.*#\1#p'
178.62.236.250
root#yakkety:~#
Debian Jessie
root#jessie:~# sed -r -n 's#"##g;s#^PRETTY_NAME=(.*)#\1#p' /etc/os-release
Debian GNU/Linux 8 (jessie)
root#jessie:~# [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's#.*inet (.*)/.*brd.*#\1#p' || ip addr show dev eth0 | sed -n -r 's#.*inet (.*)/.*brd.*#\1#p'
192.81.222.54
root#jessie:~#
CentOS 6.8
[root#centos68 ~]# cat /etc/redhat-release
CentOS release 6.8 (Final)
[root#centos68 ~]# [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's#.*inet (.*)/.*brd.*#\1#p' || ip addr show dev eth0 | sed -n -r 's#.*inet (.*)/.*brd.*#\1#p'
162.243.17.224
10.13.0.5
[root#centos68 ~]# ip route get 1 | awk '{print $NF;exit}'
162.243.17.224
[root#centos68 ~]#
Fedora 24
[root#fedora24 ~]# cat /etc/redhat-release
Fedora release 24 (Twenty Four)
[root#fedora24 ~]# [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's#.*inet (.*)/.*brd.*#\1#p' || ip addr show dev eth0 | sed -n -r 's#.*inet (.*)/.*brd.*#\1#p'
104.131.54.185
10.17.0.5
[root#fedora24 ~]# ip route get 1 | awk '{print $NF;exit}'
104.131.54.185
[root#fedora24 ~]#
It seems like that command ip route get 1 | awk '{print $NF;exit}' provided by link is more accurate, what's more, it more shorter.
There's a node package for everything. It's cross-platform and easy to use.
$ npm install --global internal-ip-cli
$ internal-ip
fe80::1
$ internal-ip --ipv4
192.168.0.3
This is a controversial approach, but using npm for tooling is becoming more popular, like it or not.
If you know the network interface (eth0, wlan, tun0 etc):
ifconfig eth0 | grep addr: | awk '{ print $2 }' | cut -d: -f2
ifconfig | grep "inet addr:" | grep -v "127.0.0.1" | grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | head -1
ifconfig $(netstat -rn | grep -E "^default|^0.0.0.0" | head -1 | awk '{print $NF}') | grep 'inet ' | awk '{print $2}' | grep -Eo '([0-9]*\.){3}[0-9]*'
Works on Mac, Linux and inside Docker Containers:
$ hostname --ip-address 2> /dev/null || (ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p' | awk '{print$1; exit}')
Also works on Makefile as:
LOCAL_HOST := ${shell hostname --ip-address 2> /dev/null || (ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p' | awk '{print $1; exit}')}
For linux, what you need is this command:
ifconfig $1|sed -n 2p|awk '{ print $2 }'|awk -F : '{ print $2 }'
type this in your shell and you will simply know your ip.
This is easier to read:
ifconfig | grep 'inet addr:' |/usr/bin/awk '{print $2}' | tr -d addr:
If you have npm and node installed : npm install -g ip && node -e "const ip = require('ip'); console.log(ip.address())"

Resources