Question

tl;dr A bash script which requires SUDO works fine when called manually, but does not work when called by crontab, even though it was add to crontab using sudo crontab -e

I am trying to automate my connection to my vpn proxy such that the vpn connection is turned on at midnight and off at 7:15AM. In order to automate it, I wrote the following bash script, located at /usr/local/bin/cloak.sh.

#!/bin/bash

LOG_FILE=/home/declan/log/cloak.log

LogEntry()
    {
        while read data
        do
            echo "$(date "+%Y %m %d %T") ; $data" >>$LOG_FILE 2>&1;
        done
    }

echo "---------------------" | LogEntry

if [ $1 -eq 1 ]
then
    echo "Turning Cloak On" | LogEntry 
    /etc/init.d/openvpn start proxpn.miami | LogEntry
else
    echo "Turning Cloak Off" | LogEntry
    /etc/init.d/openvpn stop | LogEntry
fi

echo "---------------------" | LogEntry
echo " " | LogEntry

My vpn is working and I have confirmed that the script is executable and that it works by checking my IP address before and after calls to the script, turning the VPN on (1 as parameter) or off (0 as parameter).

declan@mx:~/log$ wget http://ipecho.net/plain -O - -q ; echo
74.196.220.81 <<-- This is my real IP address
declan@mx:~/log$ sudo /usr/local/bin/cloak.sh 1 <<-- Turn the VPN on
declan@mx:~/log$ wget http://ipecho.net/plain -O - -q ; echo
173.0.8.33 <<-- This is my VPN IP address
declan@mx:~/log$ sudo /usr/local/bin/cloak.sh 0 <<-- Turn the VPN off
declan@mx:~/log$ wget http://ipecho.net/plain -O - -q ; echo
74.196.220.81 <<-- Back to my real IP address
declan@mx:~/log$

I add this script to cron, using sudo crontab -e to ensure that sudo is running the script, with the following lines in the crontab

# Cloak on at midnight, off at 7:15AM
0 0 * * * /usr/local/bin/cloak.sh 1
15 7 * * * /usr/local/bin/cloak.sh 0

If I look at the contents of the log, /home/declan/log/cloak.log, it shows that the cron job is being executed at the correct time.

The problem is that when I check my IP address after the cron job tries to start the VPN, my real IP address is still being used. My only guess is that somehow the cron job is not being called with sudo rights, but I can't understand why.

Any help would be appreciated. I am also open to any suggestions on alternative approaches, different scripts, etc...

Thanks Declan

Was it helpful?

Solution

Added the following to my crontab and now everything is working as intended.

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

OTHER TIPS

The question is... "why use sudo?" you need a service restart which is a root operation. Edit the /etc/crontab and add the line like this:

0 0 * * * root /usr/local/bin/cloak.sh 1
15 7 * * * root /usr/local/bin/cloak.sh 0

and it should it work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top