1

I have two servers in my network and I transfer some of the data from one server to the other. I wrote a script to accomplish this and it works fine when I run it manually. However, when I include it in crontab in order to automate the process, it will not mount the external server even though the script runs. I send as much info to a log as possible but, no mount errors are reported, just the fact that it did not connect.

This is the script:

#!/bin/bash
LOGFILE="/var/log/SRV1.log"
echo $(date +%Y-%m-%d_%H:%M:%S)"  --- Begins Now" | tee -a ${LOGFILE} 
StartTime="$(date +%s)"
echo "Connecting to SRV1" | tee -a ${LOGFILE}
mount.cifs //192.168.1.200/share /media/SVR1 -o user=username,pass=pwd | tee -a ${LOGFILE}

The file is owned by root:root with 755 permissions. (I know I could tighten that up but, I'm still just experimenting).

2
  • Thank you steeldriver. Great answer! The routine now works in cron.
    – Rick
    May 27, 2017 at 18:35
  • Rick: you should accept @steeldriver answer below the next time you sign on. Apr 26, 2020 at 2:05

1 Answer 1

5

The cron program runs in a very limited environment - you can see that for example if you create a crontab containing

* * * * * /usr/bin/printenv > /tmp/cronenv

and then look at the resulting file:

$ cat /tmp/cronenv
LANGUAGE=en_CA:en
HOME=/home/steeldriver
LOGNAME=steeldriver
PATH=/usr/bin:/bin
LANG=en_CA.UTF-8
SHELL=/bin/sh
PWD=/home/steeldriver

The same applies to root crontabs (i.e. jobs submitted using sudo crontab -e):

LANGUAGE=en_CA:en
HOME=/root
LOGNAME=root
PATH=/usr/bin:/bin
LANG=en_CA.UTF-8
SHELL=/bin/sh
PWD=/root

In particular, the default PATH only contains /bin and /usr/bin; that would be fine for mount:

$ which mount
/bin/mount

however that won't work for mount.cifs for example, since it's in /usr/sbin:

$ which mount.cifs
/sbin/mount.cifs

The solution is either:

  1. always use the full absolute path for executable programs in scripts to be run as cron jobs; e.g.

    /usr/sbin/mount.cifs //192.168.1.200/share /media/SVR1 -o user=username,pass=pwd | tee -a ${LOGFILE}
    

or

  1. add a suitable PATH assignment at the top of such scripts e.g.

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

NOTE: Jobs run from the system /etc/cron.d directory have a more extensive path set explicitly in /etc/crontab:

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .