Feedback

type to search

How can I run crontab jobs only when connected to a particular network?

Asked by [ Editor ] , Edited by Egon Willighagen [ Editor ]

I have a script to back up my online email, which I now run with a crontab. But I would like to run the backup script only when I am attached to a particular network. Is that possible without writing an intermediate script run by crontab that checks my IP and then conditionally runs the backup script? That is, is there a utility in Debian that simplifies this scenario?

or Cancel

4 answers

1

helmut [ Editor ]

Maybe you can hook into the networking scripts? You can place shell scripts in /etc/network/ip-up.d. They are executed whenever you ifup any network interface (it is stored in the IFACE environment variable). You can even configure this hook script via /etc/network/interfaces. If you write a line “foo bar” below an interface definition, there is an environment variable IF_FOO=bar.

or Cancel
1

red onion [ Editor ]

Other replies are good. You need to look for some unique factor which distinguishes one network from the other. It might be IP address, default route, name server etc. Might not be easy – after all one 192.168.1.0/24 is probably going to have similarities to another.

Here’s another idea: If you are using DHCP the then check the “domain” or “search” name in /etc/resolv.conf – this file normally gets dynamically updated by DHCP when you get allocated an IP address.

You don’t need an intermediate script – just an if/then at the start of your script.

or Cancel
1

oz123 [ Editor ]

You can parse the IP address returned from /sbin/ifconfig, and add a conditional:

    if ip X.X.X.X:
           do something

    else:
          exit quietly.



Let this script run always on your cron. This will not change your system load …

Alternatively, you can add a hook to the networking script like helmut said, and comment the line in crontab when the network is disconnected. It might be VERY elegant, but I am not sure you want to spend to much time on that … a check in the beginning of the script if a network is available is very easy…

or Cancel

Your answer

You need to join Debian to complete this action, click here to do so.