1

I'm currently utilising a cron job which runs a backup script every evening to back up my documents to a networked machine over ssh, using rsync. The contents of my backup script:

#! /bin/bash
rsync -vaz --progress -s -e "ssh" /store/Documents user@server:/home/user/Backup

and my crontab:

0 20 * * * /home/user/backup.sh > /home/user/backup.log

Obviously this will only work while I am connected to my home network, and the networked computer is available. I would like to either edit my script or cron job to only run when connected to my home network. How would I go about doing this?

Running Ubuntu Mate 16.04.2.

Any help much appreciated.

1

I use a simple function like this to test whether my NAS can be reached:

function whereamI {

# Can we reach the NAS from our LAN?

/bin/ping -c1 $1 &> /dev/null

if [ ! $? == 0 ]; then
        return 1
fi

# double-check

/usr/bin/nslookup $1 | grep -i $2 &> /dev/null
if [ ! $? == 0 ]; then
        return 1
fi

return 0

}

and then:

whereamI TheIPOfMyNAS  TheNameOfMyNAS
if [ ! $? == 0 ]; then
      exit 1
fi
  • Depending on what you are trying to do the IP isn't a good criterion, since it's likely to be a 192.168.0.nnn as found in most home networks. Using the name is OK if the name come from some outside box (router or else), but if you have added it to your /etc/hosts then it will be resolved anywhere. In other words, visit a friend and your PC will feel at home. IP can however be enough to discriminate between home (192.168.*.*) and work (10.*.*.*). – xenoid May 30 '17 at 21:50
  • @xenold 1. I use 192.168.73.0/24 and so on, and I always suggest to everyone to do the same. 2. My suggestion also works on more complex configuration (while yours does not), where more than one LAN is linked via VPN to others. I have joined my lab's LAN, my two home LANS this way, and the above connects to the NAS irrespective of where precisely I am. – MariusMatutiae May 31 '17 at 4:20
1

To identify your network you can identify the MAC address of your gateway:

Bash code for this:

function gatewayMAC {
    gatewayIP=$(route -n | grep -e '^0\.0\.0\.0' | tr -s ' ' | cut -d ' ' -f 2)

    if [[ ! -z "$gatewayIP" ]]
    then
        # Identify the gateway by its MAC (uniqueness...)
        gatewayData=($(arp -n $gatewayIP | grep -e $gatewayIP | tr -s ' '))
        if [[ "${gatewayData[1]}" == "(incomplete)" ]]
        then
            echo ""
        elif [[ "${gatewayData[2]}" == "--" ]]
        then 
            echo ""
        else
            echo "${gatewayData[2]}"
        fi
    fi
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.