DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Autodetect Ethernet Cable

04.29.2009
| 4254 views |
  • submit to reddit
        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 <tokland@gmail.com>
#
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
    

Comments

Snippets Manager replied on Wed, 2009/04/29 - 11:33am

This script may be useful to see how the carrier of a ethernet interface can be read, but if you really want to enable/disable network profiles based on cable plugs, use the package "ifplugd".