Get ethernet IP address....need scripting help

roiegat
Contributor III

So we have a script which find the WIFI and Ethernet IP address and then determines which network interface to turn off. The current script uses this method:

ether=$(networksetup -listallnetworkservices | Grep -m1 'Ethernet')
wireless=$(networksetup -listallnetworkservices | Grep -m1 'Wi-Fi')

echo "Ethernet Name: $ether"
echo "Wireless Name: $wireless"

if [[ -n $wireless ]]; 
then
    getipaddywifi=$(networksetup -getinfo "$wireless" | awk 'NR ==2' | awk '{print $3'})
    echo "WIFI IP: $getipaddywifi"
fi

if [[ -n $ether ]];
then
    getipaddyether=$(networksetup -getinfo "$ether" | awk 'NR ==2' | awk '{print $3'})
    echo "ETHERNET IP: $getipaddyether"

fi

The problem is that some users are using fancy adapters and docks and it's reporting they have ethernet addresses when they actually don't. So I'd like to have it cycle through all the network services with Ethernet in the name, find ip any have an IP, and then put it in the $getipaddyether value. Any thoughts?

5 REPLIES 5

perrycj
Contributor III

I use this as an EA, but can be used as a script as well. Hopefully it helps you out. Works well for me.

#!/bin/bash

# Create result string.
RESULT=""

# Generate list of all active network device ports (e.g. en0, en1).
DEVICE_PORTS="$(ifconfig | awk -F: '/<UP,BROADCAST,SMART,RUNNING,/{print $1}' | sort 2> /dev/null)
$(ifconfig | awk -F: '/<UP,POINTOPOINT,RUNNING,/{print $1}' | sort 2> /dev/null)"

# Save output of networksetup for future lookup of friendly port names.
NETWORKSETUP=$(networksetup -listallhardwareports)

# Iterate through active ports.
for PORT in $DEVICE_PORTS; do

    # Get IP address of this port.
    THIS_IP=$(ifconfig "$PORT" | awk '/inet /{print $2}' 2> /dev/null)

    # If the IP is not blank, then add its information to the result string.
    if [[ "$THIS_IP" != "" ]]; then

        THIS_NAME=$(echo "$NETWORKSETUP" | sed -n "/Device: $PORT/{g;1!p;};h" | awk '{print substr($0, index($0,$3))}')

        # If the port doesn't have a name in networksetup, use "Other."
        if [[ -z $THIS_NAME ]]; then

            # For interfaces with no name in networksetup, we have to resort to system_profiler. Would love to combine this grep/head/awk. Open to suggestions.
            THIS_NAME=$(system_profiler SPNetworkDataType | grep -B3 "BSD Device Name: $PORT" | head -1 | colrm 1 4 | awk -F: '{print $1}')

            if [[ -z $THIS_NAME ]]; then

                # If we still don't have a usable name, use "Other."
                THIS_NAME="Other"

            fi

        fi

        # Add a line feed between each port's output.
        if [[ -n $RESULT ]]; then
            RESULT+="
"
        fi

        RESULT+="$THIS_NAME ($PORT): $THIS_IP"
    fi

done

# Send the result string back to the JSS.
echo "<result>$RESULT</result>"

exit 0

stevewood
Honored Contributor II
Honored Contributor II

I use the following script with a LaunchDaemon to fire it:

#!/bin/bash

# Name:  swapNetwork.sh
# Date:
# Purpose:  disable the wi-fi port when ethernet is plugged in
# Original JAMF Nation post:  https://jamfnation.jamfsoftware.com/discussion.html?id=1441#respond
# Credit to Jonathan Synowiec for this
# Use in conjunction with a LaunchDaemon

##
# Define wireless interface "en" label.
wifiInterface=$(networksetup -listallhardwareports | grep 'Wi-Fi' -A1 | grep -o en.)
##
# Define wireless interface active status.
wifiStatus=$(ifconfig "${wifiInterface}" | grep 'status' | awk '{ print $2 }')
##
# Define wireless interface power status
wifiPower=$(networksetup -getairportpower "${wifiInterface}" | awk '{ print $4 }')
##
# Define non-wireless interface "en" labels.
ethernetInterface=$(networksetup -listallhardwareports | grep 'en' | grep -v "${wifiInterface}" | grep -o en.)
##
# Define non-wireless IP status.
ethernetIP=$(for i1 in ${ethernetInterface};do
  echo $(ifconfig "${i1}" | grep 'inet' | grep -v '127.0.|169.254.' | awk '{ print $2 }')
done)
##
# Disable active wireless interface if non-wireless interface connected.
if [[ "${ethernetIP}" && "${wifiStatus}" = "active" ]] || [[ "${ethernetIP}" && "${wifiPower}" = "On" ]]; then
  networksetup -setairportpower "${wifiInterface}" off
  touch /var/tmp/wifiDisabled; fi
##
# Enable inactive wireless interface if previously disabled by daemon.
if [[ "${ethernetIP}" = "" && "${wifiStatus}" = "inactive" ]] || [[ "${ethernetIP}" = "" && "${wifiPower}" = "Off" ]]; then
  if [[ -f "/var/tmp/wifiDisabled" ]]; then
    rm -f /var/tmp/wifiDisabled
    networksetup -setairportpower "${wifiInterface}" on; fi
fi

## update the JSS
checkjss=`/usr/sbin/jamf checkJSSConnection -retry 0 | grep "The JSS is available"`

if [ "$checkjss" == "The JSS is available." ]; then
    /usr/sbin/jamf log
fi

##
# Sleep to prevent launchd interpreting as a crashed process.
sleep 10
exit 0

Then the LaunchDaemon is simply this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.yourcompany.swapnetwork</string>
    <key>ProgramArguments</key>
    <array>
        <string>/path/to/your/script/swapNetwork.sh</string>
    </array>
    <key>RunAtLoad</key>
    <false/>
    <key>StartInterval</key>
    <integer>15</integer>
</dict>
</plist>

That will watch for when an ethernet cable is plugged in and disable wifi. Then when the cable is unplugged it re-enables wifi. I've had luck with Thunderbolt adapters, Thunderbolt Cinema Displays, and USB ethernet adapters.

swapNetwork Script

Not applicable

Same idea, not my code, works well everywhere I've used it:

#!/bin/bash

# original from http://www.grivet-tools.com/blog/2015/automatically-turn-off-wireless-osx/

# Set toggle for found IP on an interface to FALSE to start
IPFOUND=
# Determine Current OS Version
OSVERSION=`sw_vers -productVersion | cut -d. -f2`
# Get list of possible wired ethernet interfaces
INTERFACES=`networksetup -listnetworkserviceorder | grep "Hardware Port" | grep "Ethernet" | awk -F ": " '{print $3}'  | sed 's/)//g'`
# Get list of Wireless Interfaces
WIFIINTERFACES=`networksetup -listallhardwareports | tr '
' ' ' | sed -e 's/Hardware Port:/'$'
/g' | grep Wi-Fi | awk '{print $3}'`

# Look for an IP on all Ethernet interfaces.  If found set variable IPFOUND to true.
for INTERFACE in $INTERFACES
do
  # Get Wired LAN IP (If there is one other then the loopback and the self assigned.)
  IPCHECK=`ifconfig $INTERFACE | egrep 'inet [0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}' | egrep -v '127.0.0.1|169.254.' | awk '{print $2}'`
  if [ $IPCHECK ]; then
    IPFOUND=true
  fi
done

# For OS X Mavericks, Yosemite, El Capitan
if [ "$OSVERSION" == "9" -o "$OSVERSION" == "10" -o "$OSVERSION" == "11" ]; then
  if [ $IPFOUND ]; then
    /usr/sbin/networksetup -setairportpower $WIFIINTERFACES off || exit 1
    echo "Turning OFF wireless on card $WIFIINTERFACES."

  else
    /usr/sbin/networksetup -setairportpower $WIFIINTERFACES on || exit 1
    echo "Turning ON wireless on card $WIFIINTERFACES."

  fi
fi

# This sleep prevents LaunchDaemons from thinking the script failed and running it again.
sleep 10

roiegat
Contributor III

Thanks for the help guys. I'm modifying the top version for our needs. For security purposes it does a little more then just turn off a network service, but can't reveal all the details. Appreciate the help.

mvught
Contributor

I have edit some things to make it useful for more devices:

#!/bin/bash
# Original: https://github.com/jediknight112/Automatically-Turn-off-WiFi-in-OSX/blob/master/wireless.sh
# Edit: More Network interfaces

# Determine Current OS Version
OSVERSION=`uname -a | awk '{print $3}' | awk 'BEGIN {FS = "."} ; {print $1}'`
# Get list of possible wired ethernet interfaces
INTERFACES1=`networksetup -listnetworkserviceorder | grep "Hardware Port" | grep "Ethernet" | awk -F ": " '{print $3}'  | sed 's/)//g'`
INTERFACES2=`networksetup -listnetworkserviceorder | grep "Hardware Port" | grep "USB" | awk -F ": " '{print $3}'  | sed 's/)//g'`
INTERFACES3=`networksetup -listnetworkserviceorder | grep "Hardware Port" | grep "Dell" | awk -F ": " '{print $3}'  | sed 's/)//g'`
# Get list of Wireless Interfaces
WIFIINTERFACES=`networksetup -listallhardwareports | tr '
' ' ' | sed -e 's/Hardware Port:/'$'
/g' | grep Wi-Fi | awk '{print $3}'`

# Look for an IP on all Ethernet interfaces.  If found set variable IPFOUND to true.
for INTERFACE1 in $INTERFACES1
do
  # Get Wired LAN IP (If there is one other then the loopback and the self assigned.)
  IPCHECK1=`ifconfig $INTERFACE1 | egrep 'inet [0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}' | egrep -v '127.0.0.1|169.254.' | awk '{print $2}'`
  if [ $IPCHECK1 ]; then
    IPFOUND=true
  fi
done

# Look for an IP on all Ethernet interfaces.  If found set variable IPFOUND to true.
for INTERFACE2 in $INTERFACES2
do
  # Get Wired LAN IP (If there is one other then the loopback and the self assigned.)
    IPCHECK2=`ifconfig $INTERFACE2 | egrep 'inet [0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}' | egrep -v '127.0.0.1|169.254.' | awk '{print $2}'`
    if [ $IPCHECK2 ]; then
     IPFOUND=true
    fi
done

# Look for an IP on all Ethernet interfaces.  If found set variable IPFOUND to true.
for INTERFACE3 in $INTERFACES3
do
 # Get Wired LAN IP (If there is one other then the loopback and the self assigned.)
    IPCHECK3=`ifconfig $INTERFACE3 | egrep 'inet [0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}' | egrep -v '127.0.0.1|169.254.' | awk '{print $2}'`
    if [ $IPCHECK3 ]; then
      IPFOUND=true
    fi
done

# For OSX 10.7 (#11) Lion and OSX 10.8 (#12) Mountain Lion and 10.9 (#13) Mavericks, Yosemite (#14), El Capitan (#15), Serria (#16), High Serria (#17)
  if [ $IPFOUND ]; then
    /usr/sbin/networksetup -setairportpower $WIFIINTERFACES off || exit 1
    echo "Turning OFF wireless on card $WIFIINTERFACES."
    logger "wireless.sh: turning off wireless card ($WIFIINTERFACES) because an IP was found on a wired card."
  else
    /usr/sbin/networksetup -setairportpower $WIFIINTERFACES on || exit 1
    echo "Turning ON wireless on card $WIFIINTERFACES."
    logger "wireless.sh: turning on wireless card ($WIFIINTERFACES) because NO IP was found on a wired card."
  fi

# This sleep prevents LaunchDaemons from thinking the script failed and running it again.
sleep 5