Execute Shell Script on Connecting to Home Network to Sync Data to NAS
Idea
I was looking for a way to synchronize my notebook data to the NAS each time i connect to the home network. The network manager in ubuntu offers a way to execute scripts that are located in /etc/NetworkManager/dispatcher.d/. The script receives two arguments, the first being the interface name of the device just activated, and second an action. You can find more detail info about NetworkManager here: http://manpages.ubuntu.com/manpages/utopic/man8/NetworkManager.8.html .
Thinking about the implementation of the script i want it to perform the following tasks:
- Determine SSID and verify if it matches my home network
- Mount the shared folder from NAS
- Sync home folder to a mounted NAS folder with rsync.
- Write the progress of the synchronization into a log file.
Scripts
As i played with the initial implementation i found out that it is necessary to separate the rsync command from the NetworkManagers dispatcher script. Thats because the rsync can actualy take long time to finish the job and the NetworkManager has a timeout of 3 seconds that applies to each dispatcher script it runs. If the script exceeds the 3 seconds, the NetworkManager tries to kill the script.
Here is the dispachter script
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|
Notice line 17 where the dispatcher script executes the sync script as a background process.
Following values need to be set:
1 2 3 |
|
And here is the second part, the script that takes care of the synchronization of my home directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
In line 19 you can see the rsync command with its options. Each sync attempt is storred in a log file. The list of excluded directories and files is stored in a file (line 7). In line 21 i tried to create a dialog window that informs me after the syncing was succesffully completed. But unfortunately since the job runs as root i was not able to display the window under the actual user context.
1 2 3 4 |
|
Location & Permissions
Now all we need to do is to put the dispatcher script into the directory /etc/NetworkManager/dispatcher.d/, change ownership to root and make it executable. I called it wlanIsOnHomeNetwork.
1 2 |
|
Links
http://www.techytalk.info/start-script-on-network-manager-successful-connection/ https://wiki.ubuntu.com/OnNetworkConnectionRunScript