Search code examples
linuxbashnetwork-programmingwifi

Bash script to bring up and down a wireless interface on loop


If I have found the following code from another post regarding an Ethernet connection. I want to do the same thing with the wireless network card which is wlan0 on my machine. I figured that I would try swapping the iface to wlan0 and then put the ping as my router however it hasn't worked.

#!/bin/bash

timeout=5         # delay between checks
pingip='8.8.8.8'   # what to ping
iface="eth0"
LOG_FILE="/var/log/syslog"
isdown=0            # indicate whether the interface is up or down
                   # start assuming interface is up

while true; do
    LOG_TIME=`date +%b' '%d' '%T`
    if ping -q -c 2 "$pingip" >> /dev/null ; then      # ping is good - bring iface up
        if [ "$isdown" -ne 0 ] ; then
            ifup $iface && isdown=0
            printf "$LOG_TIME $0: Interface brought up: %s\n" "$iface" | tee -a $LOG_FILE
        fi
    else                                 # ping is bad - bring iface down
        beep -f 4000
        if [ "$isdown" -ne 1 ] ;  then
            ifdown $iface && isdown=1
            printf "$LOG_TIME $0: Interface brought down: %s\n" "$iface" | tee -a $LOG_FILE
        fi
    fi
    sleep "$timeout"
done

Am I barking up the wrong tree here, or do I just need to edit this a bit further. My bash skills are subpar I'm afraid.


Solution

  • I'm pretty sure that ifconfig presents on your system

    1. determine the name of your interface ls /sys/class/net, likely it's wlan0 or wlp2s0
    2. change ifup $iface and ifdown $iface to ifconfig $iface up and ifconfig $iface down respectively