Ubuntu network location detection

Ok, it’s not a full location detection as such.. I use my laptop (Ubuntu 9.04) both at home and work, as well as other places.  The problem that I had was related to how SAMBA was configured.  At home I have one workgroup name and at work I want the machine to appear in the company domain.  But also, while out and about in the big bad world I don’t want SAMBA on at all, no need to share anything with anyone.

So, to over come this and correct it at boot time I’ve come up with the simple script below.  The only other thing you need to do is prepare a couple of smb.conf files to suit the locations you’ll be in.   I have 2 smb.conf files, one for HOME and one for WORK.   I run the script from /etc/rc.local so it runs when I should have networking fully up and running. 

Here is the script:

#!/bin/bash
 
HOME=YOUR_HOME_GW_IP
WORK=YOUR_WORK_GW_IP
 
GW=`route -n | grep ^0.0.0.0| awk '{print $2}'`
 
if [ $GW = $WORK ]; then
    #echo "You're at work"
    cp /etc/samba/smb.conf.WORK /etc/samba/smb.conf
    /etc/init.d/samba restart
elif [ $GW = $HOME ]; then
    #echo "You're at home"
    cp /etc/samba/smb.conf.HOME /etc/samba/smb.conf
    /etc/init.d/samba restart
else
    #echo "You're somewhere else"
    /etc/init.d/samba stop
fi

Pretty simple really.  Hope others will find it useful.


4 Responses to Ubuntu network location detection

  1. I noticed performance problems with Sun’s samba build on S10U4. On 100 Mbit network – 700 MB file over samba was copied about 5-6 min. and over FTP just 1:46 min.
    Do you know anything about this? Can I resolve this problem with build my own samba from sources?

  2. The IP isn’t perfect, but you can mitigate the risk by changing your home network’s address from the default 192.168.0.0 network address to something less likely to be used.

  3. Yes, that is a possible problem, but I think generally it’s OK. The DNS lookup might not work for about 95% of the people unless they actually run a DNS server at home..

    Might look at doing something where it checks your external IP address and based it on that.. however with dynamic IP’s at home that’s not a good idea either really.

  4. That is a pretty straight forward to the problem. The only weakness I can see is if you are somewhere that has the same gateway IP as the one you use at home. One way to deal with this might be to get the FQDN associated with the IP address you’ve been assigned and use that to help determine where you are.