2

I am a newbie to scripting on Linux (Lubuntu), but I would like to make a script that runs a cron job only if my laptop is connected to my home wifi.

Is this possible?

I guess, I could do something with iwconfig and pull the ESSID from there with grep?

So far, I tried this and it seems to work:

#!/bin/bash
# CRON, connected to specific WIFI
clear
netid=HOFF216
if iwconfig | grep $netid
then 
    clear   
    echo "True, we are connected to $netid"
    rsync ...........
else
    clear       
    echo "False, we are not connected to $netid"
fi
6

I'd suggest running a cronjob script unconditionally (ie, regardless of whether or not you're connected to wifi). The script itself would then check for the wifi network, and exit if you're not connected to the right one.

To check which network you're connected to, I'd suggest using nmcli. It will output something like:

[jk@pororo ~]$ nmcli dev wifi list
SSID                              BSSID       MODE             FREQ       RATE       SIGNAL   SECURITY   ACTIVE  
'other-network'                   <bssid-1>   Infrastructure   2412 MHz   54 MB/s    32       WPA WPA2   no      
'some-other-network'              <bssid-2>   Infrastructure   2412 MHz   54 MB/s    25       WEP        no      
'my-network'                      <bssid-3>   Infrastructure   2462 MHz   54 MB/s    99       WPA2       yes

To script this, I'd suggest something like:

# extract the essid from nmcli output
essid=$(nmcli dev wifi list | sed -n "s/^'\([^']*\)'.*yes\s*$/\1/p")

# check for my-network, exit otherwise
[ "$essid" == "my-network" ] || exit

# now we know we're connected to my-network
  • For a script, it might be easier to parse the output of nmcli dev list iface eth1 or iw dev eth1 link (replacing eth1 with the appropriate interface). – James Henstridge Jun 14 '12 at 1:07
  • nmcli dev list is a little tricky, as you need to find the active AP. nm dev wifi list looks promising though, I'll update to use that. – Jeremy Kerr Jun 14 '12 at 1:28
  • 1
    You can reduce the seddery by using something like nmcli -t -f name con show --active. This will give you a list of network names that are active with no other extraneous information. Combine with grep -q. – Robie Basak Feb 1 '17 at 23:48
2

Based on your work I'm now using the following in my script:

# Check if we are home
essid=`nmcli con status|grep <ESSID>|awk '{print $1}'`
[ "$essid" = "<ESSID>" ] || exit
0

On Ubuntu 16.10 Yakkety, nmcli tool version 1.2.4, the output looks different. I ended up using the following:

essid=$(nmcli dev wifi list | tail -n +2 | sed -n -e /^*/p | awk -F ' ' '{print $2}')
[ "$essid" == "<ESSID>" ] || exit

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.