Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Autodetect Ethernet Cable

DZone's Guide to

Autodetect Ethernet Cable

·
Free Resource
This script autodetects when the ethernet cable is plugged andenable the asked network profile for the device. It is designed for Debian, but should be easily adapted to any distro.


#!/bin/bash
# Autodetects the ethernet cable plug and enable the asked network profile
#
# Usage: ethauto IFACE[=PROFILE]
#
# Example: ethauto ath0=myconf
#
# Author: Arnau Sanchez 
  
   
#
AUDIO_UP="/usr/local/sounds/misc/apert.wav"
AUDIO_DOWN="/usr/local/sounds/misc/beam.wav"

eth_status() {
  CARRIER="/sys/class/net/$1/carrier"
  cat $CARRIER || ifconfig eth0 up
  test $(cat $CARRIER) = 1
}

ifstate() {
  grep -xq "$1" "/etc/network/run/ifstate"
}

INFO=$1
IFS="=" read DEVICE PROFILE <<< "$INFO"
while true; do
  if eth_status $DEVICE && ! ifstate $INFO; then
    ifup $INFO && aplay $AUDIO_UP
  elif ! eth_status $DEVICE && ifstate $INFO; then    
    ifdown $INFO #&& aplay $AUDIO_DOWN
  fi
  sleep 1
done

  
Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}