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

Change location automatically based on network Network
It always bothered me that when I went from one place to another (work, home, friend's house) that I had to manually choose from my pre-configured Locations from the Apple menu. It seemed to me that there was enough information available to set the Location automatically whenever the wireless network changed.

So I messed around a lot, did a lot of googling and poking around, and came up with the following solution.

First, I had to have a way of changing the Location based on the wireless network I was connected to. If all the networks you connect to have unique SSIDs, this script works fine. If this is not true for you, it should be possible to change it to recognize the MAC address of the router or access point instead of the SSID, but I haven't had luck with that yet.
#!/bin/sh

#get the ssid of the network you are on
#shown on two lines; should be one with a space
ssid=`ioreg -l -n AirPortDriver | grep APCurrentSSID 
 | sed 's/^.*= "\(.*\)".*$/\1/; s/ /_/g'`

#fill in your own values for ssid and location below
if [ $ssid = "workrtr" ]
then
    location="Work"
elif [ $ssid = "homertr" ]
then
    location="Home"
elif [ $ssid = "friend" ]
then
    location="Joe"
else
    location="Automatic"
fi

#update the location
newloc=`/usr/sbin/scselect ${location} | sed 's/^.*(\(.*\)).*$/\1/'`

echo ${newloc}

#exit with error if the location didn't match what you expected
if [ ${location} != ${newloc} ]
then
    exit 1
fi

exit 0
I'm not sure where these scripts should go, but let's call it update-location.sh, put it in /root, and chmod 700 /root/update-location.sh to make it executable. Next, we have to find a script that OS X calls when the wireless network changes. The one I chose is in the Kicker bundle. There may be better places, but this is the only one that I found that worked reliably. In /System -> Library -> SystemConfiguration -> Kicker.bundle -> Contents -> Resources, you will find a file named set-hostname. You need to be root to modify this, and you should make a backup (cp set-hostname set-hostname-backup) before you begin. At the end of the script, just before exit 0, add the following line:
location=`/root/update-location.sh`
If you want to play nice with the system.log, you can also add this just below:
logger -i -p daemon.notice -t set-hostname setting location to "${location}"
That's it! I think there's a small (finite) loop that happens when scselect is called from update-locations.sh -- I think set-hostname is called again, which will again call update-locations.sh. But, the loop only runs through twice, possibly because scselect hasn't changed anything the next time through the loop. This is a little rough, so it's possible this needs a little tweaking by someone who knows more than I do. Note that I have the Developer Tools installed, and I am running 10.3.7.
    •    
  • Currently 3.83 / 5
  You rated: 5 / 5 (6 votes cast)
 
[69,537 views]  

Change location automatically based on network | 38 comments | Create New Account
Click here to return to the 'Change location automatically based on network' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Change location automatically based on network
Authored by: platte on Jan 18, '05 11:56:14AM

now we just need a script to automatically mount a list of servers for each location...



[ Reply to This | # ]
Change location automatically based on network
Authored by: sinebubble on Jan 18, '05 05:55:39PM

Mounts? Just add the command under each SSID match.
[code]
#fill in your own values for ssid and location below
if [ $ssid = "workrtr" ]
then
location="Work"
mount server:/export/home/tools /tools
elif [ $ssid = "homertr" ]
then
....
[/code]



[ Reply to This | # ]
Change location automatically based on network
Authored by: bjmorgan on Jan 18, '05 12:11:16PM

I wonder... would this work with my network at home that doesn't broadcast an SSID? In fact, neither of the networks I regularly switch to broadcast.



[ Reply to This | # ]
Change location automatically based on network
Authored by: AJB on Jan 18, '05 03:06:41PM
I've been doing something like this for a long time without using a broadcast SSID. try:
ATTACHEDWLAN=`/usr/sbin/system_profiler SPAirPortDataType|awk -F": " '/Current Wireless Network/{print $2}'`
I also test for "AirPort is currently turned off" | "wireless network not available" and then check the ethernet LAN IP as a fallback
ETHERNETIP=`/sbin/ifconfig en0 | grep netmask | awk '{print $2}'`
to put the icing on all this, I run it in a script on wake up, setting location to automatic if it fails to determine where I am, and back off with an exponential delay before repeating.

[ Reply to This | # ]
Change location automatically based on network
Authored by: bear8b on Jan 18, '05 05:52:47PM

How do you run a script on wake up? I have been looking for that trick!



[ Reply to This | # ]
Change location automatically based on network
Authored by: miggins on Jan 18, '05 08:55:20PM
You need SleepWatcher from http://www.bernhard-baehr.de/, it lets you run scripts on sleep and wake events.

[ Reply to This | # ]
Change location automatically based on network
Authored by: richwiss on Jan 18, '05 10:11:07PM

The other option is to simply list each of the SSID's at your work in this script and if it auto-connects to the wrong one, have the script set your Location to "Work" (or "Home" as the case may be) and the Location will then change you over to the correct SSID.



[ Reply to This | # ]
Change location automatically based on network
Authored by: raider on Jan 18, '05 12:29:12PM
Check out Location X

[ Reply to This | # ]
Change location automatically based on network
Authored by: AndySpry on Jan 18, '05 01:11:20PM

Although Location X allows control over more than just the network configuration, it still lacks the ability to automatically detect which network you are connected to and change the location automatically.

The application is also not AppleScriptable so the above network detection and automatical location change script can't be used to tell Location X what location to use.

So the net result is you still have to make a menu selection (Location X instead of Apple) to manually change the location without the script.

If Location X had the ability to change which volumes were mounted and to automatically switch locations it would be a great application which I would purchase in a heartbeat. As it currently exists (I checked again today) it can't even be made to work since it is not scriptable.

I solved most of this problem by having two accounts, one for work and one for home. This also lets me keep my work and home files as well as configuration separate. The automated script does just what I need. Thanks to the author for creating it.



[ Reply to This | # ]
Change location automatically based on network
Authored by: raider on Jan 18, '05 06:42:22PM
True, Location X doesn't appear to be Applescriptable.

But it *does* RUN Applescript, and shell scripts. So it can mount and unmount as you wish.

And the plugins look promising....

Drop the creator a line and let him know that what would let YOU spend your money on LocationX would be scriptability. Perhaps Applescript or making a command line LocationX that you could invoke from within a shell script or AppleScript...

[ Reply to This | # ]
Peripheral Vision
Authored by: hugomallinson on Jan 18, '05 02:06:38PM
I've been thinking the exact same thing for a month now, and just two days ago found Peripheral Vision which does exactly this, along with a slick PreferencePane. It provides hooks for connection and disconnection of network connections, usb, and firewire, as well as mounting drives and the reg'd version ($7) will run programs at each of these events.

[ Reply to This | # ]
Peripheral Vision
Authored by: zeniam1 on Jan 20, '05 11:45:21AM

This Preference Pane rocks!!!



[ Reply to This | # ]
Peripheral Vision
Authored by: lebnjay on Jan 21, '05 12:18:58AM

This preferance pane is interesting, but I don't see how to automatically change the location based on network.
can someone clue me in.



[ Reply to This | # ]
Change location automatically based on network
Authored by: cudaboy_71 on Jan 18, '05 03:47:07PM

i've wondered about automatically changing location based upon available SSID for quite a while. but, i dont think this addresses it, unless i am missing something. (most likely i am. i dont speak SED so well. but, it looks like it is just getting the SSID airport is currently using, no?)

to me this seems like putting the cart before the horse.

lemme 'splain:

my 'locations' define which SSID to join. so, when i go to work, my location profile tells the computer to join one of the 3 available SSIDs broadcasting in my area.

similarly, when i go home, my home profile joins one of two broadcasting SSIDs (dont ask).

now, somebody 'splain to me:

if the script changes the location profile based upon which SSID is connected, but the location profile is needed to define which SSID to connect to....well...it all just seems kinda circular to me. what am i missing?

now, if the script got a location based upon *avialable* SSIDs in the area, that could work. but, predefining the SSID in the script seems like it would require me to select the SSID from the airport menu.

---
if it aint broke, break it!



[ Reply to This | # ]
Change location automatically based on network
Authored by: chris_on_hints on Jan 18, '05 05:18:15PM

As I understand it, your mac will join whatever WiFi network it can, from the list of networks that:
a) you have given it permission to join automatically
b) that it knows the password for (ie keychain)
c) obviously must be available
It will just join the one which is available, without changing the location.... AFAIK, the networks arent necessarily part of a 'location'.

Now, if you need different IP settings or email settings for each different WiFi network, your mac will join the network for you, but you would have to tell it to change settings manually. I experience this between my home (manual IP setting) and my parent's house (DHCP IP address). When I got home last time, my mac joined my home network, but was trying to get an IP via DHCP... (ie still set to the parent's house location) my internet connection was only working when i remembered to change the location (to tell my machine to revert to its manual IP).

Does that make sense? At least, this is my experience of how it works....

This script looks good, as it the mac would automatically join which ever network is available, then change the location setting to whatever you told it was appropriate. You could also get the script to do additional things (like mounting specific network drives etc) by just adding them to the script at the correct place... the only risk is that which ever commands you add would be executed as root, so BE CAREFUL. Commands that might run ok in your terminal window might have slightly different behaviour (or security issues) when run as root...



[ Reply to This | # ]
Change location automatically based on network
Authored by: tomofdarkness on Jan 18, '05 06:12:40PM

I have a university wireless network that I have access to, which requires a special setup with a Network Password to logon. When I have it set to connect automatically, OS X doesn't even see that the network is there. I'd love to have a script that would try automatic, and if it didn't find anything, try that location, and if it didn't find that, try automatic again, or something... Actually, I'm having trouble describing exactly what I want, which is why I haven't actually done anything about it.



[ Reply to This | # ]
if you want to put it somewhere standard
Authored by: huzzam on Jan 18, '05 04:07:19PM

/root is a kind of funny place to put it, and guarantees that you'll need to type the path to execute it. A more standard place to put it would be /usr/local/bin (or perhaps /usr/local/sbin). That way it's in the default path, and you don't need to type "/root/update-locations.sh" to execute it; just "update-locations.sh".

peter



[ Reply to This | # ]
Change location automatically based on network
Authored by: cudaboy_71 on Jan 18, '05 08:29:49PM

i guess i've always used location manager differently than most then.

for one, i like static ips...that way i can call a machine by ip when i need it (if all else fails). plus, my work network is 192.168.1.x & my home network is 192.168.0.x...simple enough for me to change my home net...but i'm lazy.

so, my location profiles do two things:

1-reconfigure the netmask, change IP, change DNS servers
2- define which SSID to join

since i have multiple SSIDs at each location, i have a different location profile to join each. what would be nice is if i could write a script to activate each profile based on signal strength, which is what it boils down to for me --i always join the closest one to me.

as it is now, i just hit fn-opt-2 (my keyboard shortcut for the applemenu), hit a few arrow keys to my location profile, and i'm done. but, it would be nice to have it choose automatically.


---
if it aint broke, break it!



[ Reply to This | # ]
Change location automatically based on network
Authored by: richwiss on Jan 18, '05 10:08:53PM

I hate to reply to my own hint with bugs, but since I submitted it, I realized there is a small problem which has two obvious solutions, only one of which I actually know.

First, the bug: This bug occurs when you're using a wired connection and you want to use a Location that isn't "Automatic". If the update-location.sh script doesn't find a matching SSID (which will happen if there isn't one near you OR if you've got the wireless turned off), the script will set your location to Automatic. If you change the location to, say, "Work", the Kicker bundle gets called, checks your list of SSID's, doesn't find a matching one, and sets your location back to "Automatic".

And the solutions:
1. Don't have a fallback case in the update-location.sh script. In other words, remove the else statement from the end of the long if statement. This will mean if you go to a new location that you haven't seen before, you'll have to choose Automatic. For me, that's fine since I rarely use public locations.
2. Detect when you're wired - or detect that there is no wireless SSID availabe - and disable the script. Probably you could just run "ifconfig en0 " and check to see if you've got an IP address. If you have one, you can simply bail out of the script early. I can play with it a little bit - but not until later in the week. If anyone else wants to clean it up first, that's great.



[ Reply to This | # ]
Change location automatically based on network
Authored by: AJB on Jan 18, '05 10:31:24PM
I guess you missed my reply because it was nested. I check wireline IP address, and do an exponential back off with sleep after not finding a known location.

[ Reply to This | # ]
Change location automatically based on network
Authored by: mdzorn on Jan 18, '05 11:40:28PM

Am I missing someting here?

My 12in G4 laptop automatically switches locations (i.e., network locations).
I have the network set to "Automatic". Whenever a network (wireless or wired) is available, MacOSX checks them all out and connects to the one that is available. The order in the Network Status list defines the priority. I connect wireless and by Ethernet at home, at work, and various locations around the counry and never ever manually switch locations. So there is no need for an automatic script to do it either.

So I don't quite understand why you would need a script to changethe location. The program Location X is useful if and only if you want additional automatic changes, e.g., change the preferred printer, mounting disks, etc. that are specific for each location. But just to connect to your network, the Automatic Network preferences is more than enough.

For each specific network (Home, Work, Starbucks, etc.) create a location in network preferences. The Automoatic setting will select the best location from the list.

[Airport asks you whether you want to remember a specific wireless network. If you choose yes, it will automatically connect to the best available wireless network.]



[ Reply to This | # ]
Change location automatically based on network
Authored by: lagroue on Jan 19, '05 03:40:23AM

An example of usefulness of such a script :

When I'm home, my iBook acts as a server for some services (like web). It needs a fixed IP, so that other computers know how to reach it.

But when I travel, I have to switch to DHCP so that I can plug (yes, I'm old-fashioned) to the network I've come to.

The disavantage is that I have to remember to switch back to "Home" location when I come back, since DCHP stills works and that I have no clue I'm not serving any more.

This is just an example, there are certainly more cases.



[ Reply to This | # ]
Change location automatically based on network
Authored by: chris_on_hints on Jan 19, '05 08:57:59AM

As i understand it, the 'Automatic' location is just the default location where settings are to get an ip address from the server automatically (ie DHCP) for all of the different network types (Airport, ethernet, firewire etc). So whenever you connect to a network which wants you to use a specific IP address, you need to modify the network prefs to do it: For ages, my 'automatic' location had been changed to use a manual IP address, so it wasnt really automatic any more... I have renamed it 'Home' and created a new location 'Away' which has all the automatic settings. I dont think the 'Automatic' location name itself has any real relevance.



[ Reply to This | # ]
Change location automatically based on network
Authored by: mdzorn on Jan 20, '05 12:21:45AM
The Apple documentation states regarding the Automatic Network Preference:
This (http://docs.info.apple.com/article.html?artnum=106800) is the help I found on the Apple support site. It seems to apply to 10.2, but from what I can see a "Port Configuration" is the same as a new "Network Location". In this help article Apple recommends duplicating a Port Configuration and customizing it for each location. Then Automatic will be able to pick one of multiple configurations, i.e., scan through the defined Network Locations until it finds one that works or give up if it doesn't.

[ Reply to This | # ]
Update Location on Wake
Authored by: colter on Jan 26, '05 04:44:39PM
After combining several of the hints here, this is what I finally got working for me: First, I installed SleepWatcher so that I can trigger the script when I wake from sleep. Given how I work, that's enough for me. Then I created /usr/local/bin/update-location.sh:

#!/bin/sh

#get the name of the wireless network you are on
#shown on two lines; should be one with a space
wlan=`/usr/sbin/system_profiler SPAirPortDataType | 
        awk -F": " '/Current Wireless Network/{print $2}'`

#look up the status
location=`grep -i "IT Airport" .wlans | awk -F"\t" '{print $2}'`
if [ "$location" = "" ] 	# If we didn't find the network
then
	location="Automatic"	# Default to Automatic
fi

#update the location
newloc=`/usr/sbin/scselect "${location}" | sed 's/^.*(\(.*\)).*$/\1/'`

echo ${newloc}

#exit with error if the location didn't match what you expected
if [ "${location}" != "${newloc}" ]
then
    exit 1
fi

exit 0
Then in ~/.wakeup

#!/bin/sh

/usr/local/bin/update-location.sh
All this does is call the above script when the computer wakes. This way, you can easily add other tasks while keeping the location-switching code separate. I wanted the list of locations to be easily editable, so I created a tab-delimited file at ~/.wlans

Home Airport\tAutomatic
Work Airport\tWork Location
tmobile\tStarBucks
It's just a list of wireless network - location pairs separated by a tab. If the update-locations.sh script doesn't find an entry, it will default back to Automatic. This works for me, ymmv. Like I said, this is mainly a conglomeration of other hints, but I thought I'd pass it on for posterity.

[ Reply to This | # ]
Update Location on Wake
Authored by: hintbw on Mar 25, '05 02:31:20PM

I found I had to make the following change in the script (see below) in order for it to work for me. It is an excellent script, now I don't ever have to remember to change locations.

The one other element to the script that I would like to add is for it to change locations based on ip address (i.e. have it check for a wired ethernet ip address and set the location depending on the ip address it is currently getting, if it doesn't find a wired ip address to fall back to the current script to check for a wireless network and set the location accordingly.

Thanks for the script Colter

Here's the original code


#look up the status
location=`grep -i "IT Airport" .wlans | awk -F"\t" '{print $2}'`

Here's what I had to change it to get it to work for me.


#look up the status
location=`grep -i "$wlan" .wlans | awk -F"\t" '{print $2}'`


[ Reply to This | # ]
Appletalk
Authored by: jason mark on Jan 27, '05 07:47:43PM

One frusterating thing about OSX is that Appletalk can ONLY run on EITHER wireless or the LAN. 60% of the time when in the office I'm on the LAN, and when doing things like connecting to our internal filemaker server, or sharing iTunes I want the speed of the LAN. The rest of the time I'm on wireless (conference room, someone else's desk, whatever). In those cases I'd love it if Appletalk could just "shift over" to the working network, but it can't.

So I have 2 "locations" - LAN and WAN. The ONLY reason I have to switch is to use Appletalk to get to servers, but it is an important thing...



[ Reply to This | # ]
Appletalk
Authored by: The_Keymaker on Apr 01, '05 02:04:27AM

I agree that the AppleTalk switching is really clunky. I wish Apple would come up with something more Mac-like ;-).

This isn't much help, but it is a little (very little) easier than switching locations. If you set it up correctly, you can turn Airport on and off as needed using the Airport status icon in the menu bar and AppleTalk will be automatically switched for you. I find toggling Airport from the Airport status icon in the menu bar easier than digging into the Location menu under the Apple Menu. As an added benefit you only need one "Automatic" location to make this work.

Here's how I've set it up.

On your "Automatic" location, arrange the Network Port Configurations (System Preferences > Network > Show > Network Port Configurations) so that Airport is first in the list and Built-in Ethernet is second (you can drag them to arrange them). Configure the Airport and Built-in Ethernet settings on this location for your wireless and wired connections respectively. Be sure to tick the checkbox to "Show Airport status in menu bar" under the Airport tab of the Network preference pane.

Next, with Airport on, set AppleTalk to active on the Airport configuration. Now when you are plugged into the wired LAN, simply turn Airport off from the status icon in the menu bar. AppleTalk will automatically switch to your Built-in Ethernet connection. When you un-plug from the wired network to go wireless, simply turn Airport back on and AppleTalk will switch back to your Airport connection.

I prefer that to switching locations. I hope that helps.



[ Reply to This | # ]
Change location automatically based on network
Authored by: galexand on Feb 19, '05 11:08:02AM

Chris said: "As I understand it, your mac will join whatever WiFi network it can, from the list of networks that:
a) you have given it permission to join automatically"

How do I alter this list of permissible networks?

I really like that it automatically joins a network, but I'd like to be able to you know add one network at each physical location, so that when I'm at home it always connects to my AP not my neighbor's, and when I'm at my friend's house, it automatically connects to his AP and not his neighbor's, etc...



[ Reply to This | # ]
Alternate ways to access the SSID
Authored by: galexand on Feb 19, '05 11:14:36AM

The ssid=`...` line from the original script didn't work for me (for some reason it worked at the shell, but from within set-hostname, it didn't *shrug*). So I found the same information burried in configd, which we can get at using scutil:

ssid=`(echo open; echo show State:/Network/Interface/en1/AirPort) | scutil | grep \ SSID | sed -e 's/^.* //'`

colter posted a script that contains nother way to obtain this information using /usr/sbin/system_profiler also.



[ Reply to This | # ]
Change location automatically based on network
Authored by: cbt on Apr 01, '05 01:15:03PM
Interesting hint! Here's one way get to fetch the MAC address of the currently active gateway. Grep against the current routing tables (ugly, but it works here):

arp `netstat -r | grep ^default | awk '{print $2}'` | \
perl -pe 's/^.* at //g' | perl -pe 's/ on .*$//g'
--
Cole

[ Reply to This | # ]
Change location automatically based on network
Authored by: BobHarris on Aug 16, '05 10:53:09PM
nit picking just a little

arp `netstat -r | grep ^default | awk '{print $2}'` | \
perl -pe 's/^.* at //g' | perl -pe 's/ on .*$//g'

can be simplified slightly by combining the grep into the awk


arp `netstat -r | awk '/^default/ {print $2}'` | \
perl -pe 's/^.* at //g' | perl -pe 's/ on .*$//g'


[ Reply to This | # ]
Change location automatically based on network
Authored by: cp on Aug 16, '05 11:12:24PM
Crikey, you call that simplified? You perl people make me laugh.
 arp `netstat -r | awk '/^default/ {print $2}'` | cut -f4 -d" "    
does exactly the same thing without fscking perl!!

cmlp

[ Reply to This | # ]
Change location automatically based on network
Authored by: mikeizzy on Jul 22, '05 05:25:06PM

In /System -> Library -> SystemConfiguration -> Kicker.bundle -> Contents -> Resources, you will find a file named set-hostname. 
Anyone have a suggestion as to where to put this script in OS X 10.4? There no longer is a set-hostname file in the Kicker.bundle.

[ Reply to This | # ]
Change location automatically based on network
Authored by: BobHarris on Aug 16, '05 10:44:01PM
Here is my SleepWatcher based automatic network location switching script.

Bob Harris


#!/bin/sh
#-----------------------------------------------------------
# MacAutoNetDetective.sh - Script to automatically set my
#                          Mac OS X Network Location after
#                          waking up from sleep.
#
#   If you are going to try and use this script then you
#   will need to customize it, so see the 
#   "CUSTOMIZE THIS SECTION" below.  You should read the
#   following comments.
#
#   This script is intended to be run by SleepWatcher
#   whenever my iBook wakes up from sleep.
#     http://www.versiontracker.com/dyn/moreinfo/macosx/17579
#     http://www.bernhard-baehr.de/
#   SleepWatcher looks for the executable script
#   $HOME/.wakeup where you should put a call to a modified
#   copy of MacAutoNetDetective.sh:
#
#       #--------------------------------------------
#       # .wakeup - SleepWatcher wakeup action script
#       #--------------------------------------------
#       # Bob Harris
#       #--------------------------------------------
#         sh $HOME/bin/MacAutoNetDetective.sh
#       #--------------------------------------------
#
#   .wakeup and MacAutoNetDetective.sh need to be made
#   executable:
#
#       chmod +x $HOME/.wakeup
#       chmod +x $HOME/bin/MacAutoNetDetective.sh
#
#       NOTE:  I had to modify the SleepWatcher 2.0.1
#              /etc/rc.wakeup script to add >/dev/null to
#              grep command:
#
#                if grep -q $shell /etc/shells >/dev/null; then
#
#              to get it to stop saying:
#
#                ...
#                if grep -q $shell /etc/shells; then
#                grep: writing output: Bad file descriptor
#                ...
#
#   I use this script because at work I need a Network
#   Location that includes proxy information configured on
#   the ethernet port, at home I use WiFi with fixed IP
#   addresses to router 10.0.1.1, and at Mom's the WiFi uses
#   a different SSID/password with the router at
#   192.168.1.1.  There is no limit to the number of Network
#   Locations this script could support as long as you can
#   find enough unique network information to determine
#   where you are waking up.
#
#   This is a very customized script, but the basic idea
#   should be usable by anyone that can figure out some
#   unique network identification while connected using
#   DHCP, and then switch to the desired Network Location.
#
#   /usr/sbin/scselect
#      Will display all the available Network Locations.
#      Mine looks something like this:
#
#      % /usr/sbin/scselect
#      Defined sets include: (* == current set)
#       96078368-4301-11D8-B301-000A95DAE736	(Automatic)
#     * 0	(at Home DSL)
#       628CF6AE-2102-11D8-ADDA-000A95DAE736	(Mom's)
#       86E16997-6E3A-11D9-B31F-000A95DAE736	(at Work)
#
#   /usr/sbin/scselect "desired location"
#      Will set a new Network Location.
#
#   /usr/sbin/netstat -nr | awk '/^default/{print $2}'
#      Will tell you your current default router IP address
#
#   /usr/sbin/arp -a
#      Seems to give the local router as well as other
#      recent IP to ethernet MAC translations.  It also
#      includes names, which can be very useful.  For
#      example Home says: AirportExtreme, Mom's says:
#      dslrouter, and work stays:
#      usa-swi-1-rtr-1.xyzcompany.net.  This could be very
#      useful in determining which network I'm attached to.
#
#   /usr/sbin/system_profiler SPAirPortDataType |\
#         awk -F": " '/Current Wireless Network/{print $2}'
#      Can find your Airport SSID.
#                          
#   /usr/bin/grep nameserver /etc/resolv.conf
#      Will tell you your current DNS servers
#
#   /sbin/ifconfig -a
#      Will tell you your current IP address
#
#   /usr/sbin/traceroute -m 5 whatisyourip.com
#      Might show you the names of some of your ISP's
#      routers, however, if any of the routers along the way
#      block tracerouter probes, you will get nothing, and
#      depending on the value of -m, suffer through a long
#      timeout.  -w 2 -q 2 can cut down on this a little.
#
# logger information can be viewed in /var/log/system.log,
#        or via Applications -> Utilities -> Console -> Logs
#        -> system.log
#                          
#-----------------------------------------------------------
# Bob Harris
#-----------------------------------------------------------
logger "${0##*/}: Start -----------------------------------"

#
# We start by setting the network to the "Automatic"
# Location, assuming this is the original default MacOSX
# setup.  It should allow us to automatically detect a
# network via Airport or ethernet, and get an IP address via
# DHCP.  That should be enough to probe for information that
# tells us were we are.
#
/usr/sbin/scselect "Automatic"
logger "${0##*/}: scselect: Automatic: status=$?"
sleep 5

#
# Get my current default router IP address.  If there is no
# default router assigned yet, wait until one appears.
#
tries=0
delay=5
announce=1
def_router=""
while [[ -z "$def_router" ]]
do
    def_router=$(/usr/sbin/netstat -nr | awk '/^default/{print $2}')
    tries=$(( $tries + 1 ))
    if [[ -z "$def_router" ]]; then
        if [[ $tries -gt $announce ]]; then
            logger "${0##*/}: netstat: no default router: tries=$tries"
            announce=$(( ( $announce + 1 ) + ( $announce / 2 ) ))
        fi
        sleep $delay
        tries=$(( $tries + 1 ))
    fi
done
logger "${0##*/}: netstat: $def_router"

#
# Get my current arp information.
#
my_arp=$(/usr/sbin/arp -a)
logger "${0##*/}: arp: $my_arp"

#==========================
# CUSTOMIZE THIS SECTION
#==========================
#
# Based on my router and arp information, choose one of my
# Network Locations.
#
# See above suggestions for other ways to find out where you
# might be, especially if your default router is not unique
# in all locations you might be roaming (for example
# 10.0.1.1 and 192.168.1.1 are very common home Cable/DSL
# router IP addresses.
#
atHOME=0
atWORK=0
atMOMS=0
MINIMUM=5
[[ "$def_router" = 10.0.1.1        ]] && atHOME=$(( $atHOME + 1 ))
[[ "$my_arp" = *AirportExtreme*    ]] && atHOME=$(( $atHOME + 1 ))
[[ "$my_arp" = *11:22:33:44:55:66* ]] && atHOME=$(( $atHOME + 10 ))

[[ "$def_router" = 10.37.151.1     ]] && atWORK=$(( $atWORK + 10 ))
[[ "$my_arp" = *mycompany.com*     ]] && atWORK=$(( $atWORK + 10 ))

[[ "$def_router" = 192.168.1.1     ]] && atMOMS=$(( $atMOMS + 1 ))
[[ "$my_arp" = *dslrouter*         ]] && atMOMS=$(( $atMOMS + 1 ))
[[ "$my_arp" = *aa:bb:cc:dd:ee:ff* ]] && atMOMS=$(( $atMOMS + 10 ))

SCORE=$MINIMUM && Location=""
[[ $SCORE -lt $atHOME  ]] && SCORE=$atHOME && Location="at Home DSL"
[[ $SCORE -lt $atWORK  ]] && SCORE=$atWORK && Location="at Work"
[[ $SCORE -lt $atMOMS  ]] && SCORE=$atMOMS && Location="Mom's"

logger "${0##*/}: Location='$Location'"

#==========================
# END CUSTOMIZATION
#==========================

#
# If we have figured out which Location we are at, then use
# scselect to set our new Network Location, otherwise, leave
# the system set to Automatic under the assumption that we
# are in a strange new place.
#
if [[ ! -z "$Location" ]]; then
    /usr/sbin/scselect "$Location"
    sts=$?
    logger "${0##*/}: scselect: $Location: status=$sts"
else
    #
    # can not figure out which location this is, so 
    # leave it set to "Automatic".
    #
    logger "${0##*/}: Could not resolve the location"
fi

logger "${0##*/}: End -------------------------------------"
exit


[ Reply to This | # ]
Program to automatically change location
Authored by: thePax on Apr 11, '07 02:22:22PM
I have written a program which will do just this. Run it once (to set up the configuration), click 'Apply' and forget all about it. Bear with me because it is currently an alpha - but I will get it finished as quickly as I can. For now, though, it works - albeit not perfectly. Even so, it could be just what you want http://web.mac.com/p_harris/iWeb/Pascal/Software_files/Locamatic.dmg

Please read the documentation before running Locamatic!

[ Reply to This | # ]
Change location automatically based on network
Authored by: wastemytime on Apr 26, '07 04:19:10AM
Here's another freeware location manager that can perform certain actions and switch locations based on Bluetooth, WiFI Airport, USB and IP address


http://thinkabdul.com/2007/04/26/automatic-location-switching-manager-perform-action-on-mac-osx-computers-based-on-bluetooth-ip-usb-and-wifi-airport/

[ Reply to This | # ]
Change location automatically based on network
Authored by: Lliwynd on May 17, '07 08:50:36PM
Hi,

I wanted something like this for a while. In general my network config doesn't change (it's DHCP based), except for the proxy configuration.

The solution I came up with was to write my own proxy.pac file that works for all locations, install it, and I'm done.

The proxy.pac file is a javascript function that gets called by the browser to find the proxy to use. I downloaded the proxy.pac files for all the different proxies I wanted to use, and then used a text editor to load them all into one file. I then created my own javascript function to do the switching. The result looks like this:



function FindProxyForURLLocationA(url, host) {
    // stuff from the location A proxy.pac FindProxyForURL() function
}

function FindProxyForURLLocationB(url, host) {
    // stuff from the location B proxy.pac FindProxyForURL() function
}

function FindProxyForURL(url, host) {
	myip = myIpAddress();

	result = "";

	if (isPlainHostName(host) || host=="127.0.0.1" || host == "localhost") {
		result = "DIRECT";
	} else if (isInNet(myip, "120.120.0.0" , "255.255.0.0")) {
		result = FindProxyForURLLocationA(url, host);
	} else if (isInNet(myip, "120.121.0.0", "255.255.0.0")) {
		result = FindProxyForURLLocationA(url, host);
	} else if (isInNet(myip, "130.120.0.0", "255.255.0.0")) {
		result = FindProxyForURLLocationB(url, host);
	} else {
		result = "DIRECT";
	}
	
	// if (!shExpMatch(url, "http:*")) {
	// 	result = result + "; DIRECT";
	// }
	
      // Return a proxy like this: "PROXY proxy.mydomain.net:3128"

	return result;
}

This approach has the added advantage that it works for all OS's.



[ Reply to This | # ]