Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

Automatically restart network on lost connection UNIX
Often times, for whatever reason, the Internet connection on my Mac will lock up. Only restarting the Airport or Ethernet interfaces seem to resolve the issue in a timely manner. (This is different from a router crash which requires a manual restart of the router - in my case an Airport Extreme.) I have developed some interconnected scripts that will automatically accomplish this task for me when attached to launchctl. This is important for me because I often have to access files over the internet and if the connection has locked up there is no way for me to access them without manual intervention.

The first script gets the active network interface. This is called by the second script which determines whether to run a matched script for either the Ethernet or AirPort interfaces. These third and fourth scripts restart either the Ethernet or AirPort connection respectively. These last two scripts can also be configured to send you an e-mail if this happens by altering the 'tobenotified" string to reflect your e-mail address in each of them. Be sure to maintain the single quotes. Or, if you do not wish to receive e-mail, comment these parts out.

Name the first script "active_interface.sh", and the second "check_internet_master.sh". This second script is what controls the rest. Attach it to lauchctl to do this automatically and never worry about a lost connection. The third and fourth scripts should be called "check_internet.sh" and "check_internet2.sh". Of course you can always name these whatever you want, but be sure to put the path to them in the scripts. Make sure to chmod all the files executable; and, unless the scripts are altered, they should also be run from the same folder.

In order for ifconfig to run with out intervention, the script needs to be run as root. Alternatively, you could make an exception for ifconfig in your /etc/sudoers file by adding the line (if you run as admin - else put %users):
%admin    ALL= NOPASSWD: /sbin/ifconfig
I don't think this is too much of a security issue.

With this setup, I find I am nearly impervious to lost connections.

=============================================================================================

#!/bin/bash
# This script determines which script to run
# based on whether your running on
# ethernet or airport.
# Name check_internet_master.sh or similar
# Attach this script to launchctl to run automatically.
AI=`./active_interface.sh`
if [ "$AI" = "en0" ]; then
echo "check_internet_master has detected" $AI "as your primary network interface. Launching matched script..."
./check_internet.sh
else
echo "check_internet_master has detected" $AI "as your primary network interface. Launching matched script..."
./check_internet2.sh

=============================================================================================

#!/bin/bash
# Script to restart the ethernet if there is no internet connection
# Name this check_internet.sh
# Alter tobenotified to reflect you email address.
IS=`/sbin/ping -c 5 74.125.226.18 | grep -c "64 bytes"`
tobenotified='xxxx@xxx.com'
if (test "$IS" -gt "2") then
       echo "Your internet connection appears to be working. Code" $IS
       internet_conn="1"
   exit
else
   echo "There appears to be a problem with your internet connection. Will check again in 10 seconds... Code" $IS
   internet_conn="0"
   sleep 10
   AA=`/sbin/ping -c 5 74.125.226.18 | grep -c "64 bytes"`
   if (test "$AA" -gt "2") then
       internet_conn="1"
       echo "Your internet connection appears to be working now. Code" $AA
       exit
   else
       echo "There is still a problem with your internet connection. Attempting to fix by ethernet restart... Code" $AA
       sudo ifconfig en0 down
       sleep 10
       sudo ifconfig en0 up
       echo "Your internet connection needed to be restarted" | mail -s "Internet Connection Down on $(date '+%m/%d/%y @ %H:%M:%S')" $tobenotified -f ipdown@no-reply.com -F "Ethernet Connection Problem"
   fi
fi

=============================================================================================

#!/bin/bash
# Script to restart the airport if there is no internet connection
# Name this check_internet2.sh
# Alter tobenotified to reflect you email address.
IS=`/sbin/ping -c 5 74.125.226.18 | grep -c "64 bytes"`
tobenotified='xxxx@xxxx.com'
if (test "$IS" -gt "2") then
       echo "Your internet connection appears to be working. Code" $IS
       internet_conn="1"
   exit
else
   echo "There appears to be a problem with your internet connection. Will check again in 10 seconds... Code" $IS
   internet_conn="0"
   sleep 10
   AA=`/sbin/ping -c 5 74.125.226.18 | grep -c "64 bytes"`
   if (test "$AA" -gt "2") then
       internet_conn="1"
       echo "Your internet connection appears to be working now. Code" $AA
       exit
   else
       echo "There is still a problem with your internet connection. Attempting to fix by airport restart... Code" $AA
       sudo ifconfig en1 down
       sleep 10
       sudo ifconfig en1 up
       echo "Your internet connection needed to be restarted" | mail -s "Internet Connection Down on $(date '+%m/%d/%y @ %H:%M:%S')" $tobenotified -f ipdown@no-reply.com -F "Airport Connection Problem"
   fi
fi

=============================================================================================
    •    
  • Currently 2.00 / 5
  You rated: 2 / 5 (6 votes cast)
 
[13,556 views]  

Automatically restart network on lost connection | 23 comments | Create New Account
Click here to return to the 'Automatically restart network on lost connection ' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Automatically restart network on lost connection
Authored by: prachigauriar on Apr 17, '12 07:49:27AM

All the $ need to be replaced with $ signs in order for this to work.



[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: kirkmc on Apr 17, '12 09:39:37AM

I've fixed it. They should be ok now.

---
Mac OS X Hints editor - Macworld senior contributor
http://www.mcelhearn.com



[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: craig.francis on Apr 17, '12 08:41:17AM

Might want to check the scripts... your missing "active_interface.sh", and they seem to have been html encoded (e.g. the dollar sign is showing up encoded with the numerical value 38 - says he trying to avoid characters that may get detected as html spam).

Also, check_internet.sh and check_internet2.sh seem to be pretty much the same, so you might want to just pass in the interface (en0/en1) as a parameter, e.g.

./check_internet.sh en1

The en1 can be accessed as the variable "dollar 1" (which again needs your interpretation).

Or just simply include all the code in "check_internet_master.sh".



[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: wallybear on Apr 17, '12 10:19:13AM

It happened to me too losing connection, and found the cause in Parallels Desktop; when I quit Parallels the network is in a "suspended" state (connection is active, but data not flowing). I then do a "ifconfig en0 down; ifconfig en0 up" and the network is restored.



[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: metiure on Apr 19, '12 03:06:05PM

@ wallybear: just change the way Parallels connects the virtual machine: use Shared Network

Edited on Apr 19, '12 03:07:46PM by metiure



[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: wallybear on Apr 20, '12 02:41:18PM

I'm sorry, I meant Virtualbox, not Parallels.
Anyway I will try the setting you suggested, but that limits the connection possibilities of the emulated machine.



[ Reply to This | # ]
Two Airport suggestions
Authored by: lullabud on Apr 17, '12 10:39:23AM

One, the command `networksetup` could replace ifconfig down/up and it does not need sudo. Eg: networksetup -setairportpower en0 off

Two, there's a command called `airport` at /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport that can give you information that might help diagnose your problem.



[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: rvamerongen on Apr 17, '12 12:54:58PM

Where is script four?



[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: Inspired on Apr 17, '12 04:13:47PM

Thanks for this.
WIll it also for for 3G data stick connections?

Mine shows up as called "Ethernet Adaptor (en2)" (not sure why, because it also created an entry called "HUAWEIMobile-Modem" but that one does not get used by the dialer software that created it).

The connection on "Ethernet Adaptor (en2)" drops quite often, and I'd love to be able to have it reconnect automatically. The "HUAWEIMobile-Modem" has dial-up related options such as automatically reconnect, etc. But as it is using the Ethernet entry, I don't have that option. Looks like your script might do the trick.



[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: xplora on Apr 17, '12 05:20:46PM

active_interface.sh is missing.



[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: slb on Apr 17, '12 05:24:26PM

Seems this hint shoulda been sussed-out first. Not sure I'd mess with this based on the replies here at this point.



[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: stevenjklein on Apr 18, '12 08:50:47AM

The directions say to "Attach it to lauchctl "

How do I do that?



[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: wallybear on Apr 18, '12 09:01:45AM
Here is a single script to do it all, and includes the functionality of the missing script:
#!/bin/bash
# This script determines which script to run
# based on whether your running on
# ethernet or airport.
# Name check_internet_master.sh or similar
# Attach this script to launchctl to run automatically.

# Alter tobenotified to reflect you email address.
tobenotified='xxxx@xxx.com'

check_internet() {
	
IS=`/sbin/ping -c 5 74.125.226.18 | grep -c "64 bytes"`
if (test "$IS" -gt "2") then
       echo "Your internet connection appears to be working. Code" $IS
       internet_conn="1"
   exit
else
   echo "There appears to be a problem with your internet connection. Will check again in 10 seconds... Code" $IS
   internet_conn="0"
   sleep 5
   AA=`/sbin/ping -c 5 74.125.226.18 | grep -c "64 bytes"`
   if (test "$AA" -gt "2") then
       internet_conn="1"
       echo "Your internet connection appears to be working now. Code" $AA
       exit
   else
       echo "There is still a problem with your internet connection. Attempting to fix by ethernet restart... Code" $AA
       sudo ifconfig $1 down
       sleep 5
       sudo ifconfig $1 up
       echo "Your internet connection needed to be restarted" | mail -s "Internet Connection Down on $(date '+%m/%d/%y @ %H:%M:%S')" $tobenotified -f ipdown@no-reply.com -F "Ethernet Connection Problem"
   fi
fi

}

# alternative to get active network port:
# AI=`ifconfig | grep -B5 " active" | grep -m1  "^...:" | sed "s/\(.*\):.*/\\1/"`

AI=`route get 0.0.0.0 | grep -m1 "interface:" | awk '{print $2}'`
echo "check_internet_master has detected" $AI "as your primary network interface..."
check_internet $AI




[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: robertcoogan on Apr 22, '12 10:32:55AM

Many, many, many thanks for this. My connection was dropping (seemingly) at random. I thought it was due to overheating, or possibly a bad Airport card (Apple tech support ruled this out). Since running this script I have seen it drop and restablish two times in the last day.

YOU ARE AWESOME!!!!




[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: wallybear on Apr 23, '12 12:57:43PM
YOU ARE AWESOME!!!!

You're welcome (mmmhmm, I think I will forward this comment to my wife, she always doubted about this... :) )

[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: rvamerongen on Apr 26, '12 08:20:57AM

Hi, nice script. Why not ping your modem first?
I do use this, because, when I can't get my modem then it is my mac. If it is the internet connection it keeps restarting for nothing when there is no internet. Also, when your mac is connected or has shares or connected to shares you will loose those as well, even when the local network works.
Luckily, not happened for three+ years for any internet failure, but my iMac has every day several times since 10.6.x

Also what is ' internet_conn="1" ' for?

The only thing what I would like to find out is, how can I get the used gate/router ip address from using a script at the mac it self ( localhost -> gate address). Any suggestions..

Edited on Apr 26, '12 08:59:33AM by rvamerongen



[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: zoharbl on Apr 19, '12 02:48:19PM

You are using a Lion aren't you?
Disconnecting after several minutes from the wifi is a well known issue - unfortunately Apple do not want to recognize that fact and this issue don't have any attention....

Have a look at this thread:
https://discussions.apple.com/thread/3190651?start=0&tstart=0



[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: bpwhistler on Apr 25, '12 10:38:46AM

"Attach it to lauchctl "

How is this accomplished for the noob? :)



[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: guyduke on Aug 02, '12 10:31:26PM

http://www.macfreek.nl/memory/Using_Launchd_on_Mac_OS_X



[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: desepticon on Apr 30, '12 05:40:33PM

Okay here's the missing script that checks the active interface just in case anyone wants it. This step is part of figuring out if you have an ethernet or airport connection, and really isn't needed unless you run both. Otherwise just use one script or the other. Also, a user above me made this into a much nicer script that I'm now using as well so you probably just scrap the original thing entirely. But, here it is just for posterity:

-------------------------------------------------------------------------------------------------------------------
#!/bin/sh

for iface in `ifconfig -lu` ; do
case $iface in
lo*) continue ;;
esac
ifconfig $iface | grep -q 'inet ' && echo $iface
done
-------------------------------------------------------------------------------------------------------------------

Thanks to the user who suggested a more simple way to do this. This is one of the first bash scripts I have made so I appreciate any suggestions. I also like the idea to ping the router first and then an outside address. That makes a lot of sense.

I myself am not using airport, but ethernet. Yet I still have this issue on lion.

For the user who wants to know how to use launchctl, I suggest looking at a tutorial or two and then using the app "Lingon". It makes things a whole lot easier. But you do still have to understand the basic concepts.

Edited on Apr 30, '12 05:54:22PM by desepticon



[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: verdekiwi on Oct 21, '12 11:09:33PM

ok this is exactly what i need.

i've connection lost every 2-3h and the best solution is rebboting the airport (no way to cheat on office' router).


the point is.... how to work on this if you are complete script noob? i have to put down in a application or something?

thanks
Giulio



[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: verdekiwi on Oct 29, '12 08:16:59AM

ok, it just simply doesnt work.

i've looked at many tutorial about script, plist, ch... but still i cant do that. it's simply doesnt work

can someone explain me in a step-by-step way?
i think doesnt worth to learn all about scripting just to solve an airport problem... -.-



[ Reply to This | # ]
Automatically restart network on lost connection
Authored by: desepticon on Oct 31, '12 09:02:31AM

You need to put a plaintext file called "com.user.checkint.plist" into /Library/LaunchDaemons/
After the file is made and placed (contents below) From terminal, type this:
sudo chown root:wheel /Library/LaunchDaemons/com.user.checkint.plist
--then enter your administrator password
sudo chmod 644 /Library/LaunchDaemons/com.user.checkint.plist
--then enter your administrator password again
sudo chmod a+x /Library/LaunchDaemons/com.user.checkint.plist
--then enter administrator password

This is the contents of that file:

<?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.user.checkint</string>
<key>LowPriorityIO</key>
<true/>
<key>ProgramArguments</key>
<array>
<string>/Users/matt/Documents/Scripts/check_internet_master.sh</string>
</array>
<key>StartInterval</key>
<integer>30</integer>
</dict>
</plist>

-----> This is what is needed to make it automatically run. Notice under ProgramArguments it references the restart check_internet_master.sh which is located in a folder called Scripts inside my Documents folder (which is in my home folder "matt"). You need to change that string to reflect where you have stored the restart script. "matt" should be whatever your home folder is called. Create a folder called Scripts in your Documents folder and put it in there. That would be the easiest way. Just make sure to change "matt" to the name of your home folder. Below is the contents of the check_internet_master.sh script. This should be a plaintext file.

# This script determines which interface to run
# on based on whether your running
# ethernet or airport.
# Name check_internet_master.sh or similar
# Attach this script to launchctl to run automatically.

# Alter tobenotified to reflect you email address.
#tobenotified='xxxx@xxx.com'

check_internet() {

IS=`/sbin/ping -c 5 74.125.226.18 | grep -c "64 bytes"`
if (test "$IS" -gt "2") then
echo "Your internet connection appears to be working. Code" $IS
internet_conn="1"
exit
else
echo "There appears to be a problem with your internet connection. Will check again in 10 seconds... Code" $IS
internet_conn="0"
sleep 5
AA=`/sbin/ping -c 5 74.125.226.18 | grep -c "64 bytes"`
if (test "$AA" -gt "2") then
internet_conn="1"
echo "Your internet connection appears to be working now. Code" $AA
exit
else
echo "There is still a problem with your internet connection. Attempting to fix by service restart... Code" $AA
sudo ifconfig $1 down
sleep 5
sudo ifconfig $1 up
# echo "Your internet connection needed to be restarted" | mail -s "Internet Connection Down on $(date '+%m/%d/%y @ %H:%M:%S')" $tobenotified -f ipdown@no-reply.com -F "Internet Connection Problem"
fi
fi

}

# alternative to get active network port:
# AI=`ifconfig | grep -B5 " active" | grep -m1 "^...:" | sed "s/\(.*\):.*/\\1/"`

AI=`route get 0.0.0.0 | grep -m1 "interface:" | awk '{print $2}'`
echo "check_internet_master has detected" $AI "as your primary network interface..."
check_internet $AI

After is is made and put in the right place you need to make it executable. Go back into terminal and type:

chmod a+x ~/Documents/Scripts/check_internet_master.sh

Then restart and it should be working.

Also you may need to manually load the launchctl item. Type this into terminal:
sudo launchctl load -w /Library/LaunchDaemons/com.user.checkint.plist
---enter adminsitrator password
To unload:
sudo launchctl unload -w /Library/LaunchDaemons/com.user.checkint.plist

Then restart and it should be working.

Edited on Oct 31, '12 09:17:11AM by desepticon



[ Reply to This | # ]