Issue running python script from Cron
-
Hi All,
I've viewed other messages re: issues running scripts with Cron but I'm still unable to resolve my issue.
I have a python script which I would like to run every few minutes (15 in this example) therefore I have added the following line to crontab using the command```
crontab -e*/15 * * * * python /usr/bin/bwmonitor.py
The script starts:
#!/usr/local/bin python
import subprocess
import re
import timef = open( '/var/log/bwmon.log','a')
dt = time.strftime("%d/%m/%Y %H:%M:%S - ")
cmd = subprocess.Popen('vnstat -i re0_vlan400', shell=True, stdout=subprocess.PIPE)and this all runs fine from an interactive session. I've noticed I don't have a /var/log/cron file either to check for any errors and have tried appending a '> mylog' to capture output to no avail. The output of running ENV is:
USER=root
SSH_CLIENT=x.x.x.x 35052 22
MAIL=/var/mail/root
HOME=/root
SSH_TTY=/dev/pts/0
LOGNAME=root
TERM=vt100
BLOCKSIZE=K
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin:/root/bin
SHELL=/bin/sh
PWD=/var/log
SSH_CONNECTION=x.x.x.x 35052 x.x.x.x 22
FTP_PASSIVE_MODE=YES
HOSTTYPE=FreeBSD
VENDOR=intel
OSTYPE=FreeBSD
MACHTYPE=i386
SHLVL=1
GROUP=wheel
HOST=pfSense
REMOTEHOST=x.x.x.x
CLICOLOR=true
LSCOLORS=exfxcxdxbxegedabagacadAny suggestions as to what else I could try? Cheers
-
You can also add the pfSense package "cron" to manage cron jobs easier.
Also make sure that you code the path of any files. I notice that "vnstat" doesn't have a full path. Cron probably can't locate the file when cron runs.
-
Thanks BBcan177,
I have used the GUI package as well as the CLI.
Didn't think about specifying the full path to vnstat, I have done that now but still getting the same issue.
Is there anyway to simulate how cron runs a command which might show an error?
Cheers.
-
Is the shebang correct?
http://stackoverflow.com/questions/6908143/should-i-put-shebang-in-python-scripts
I ran "where python" and it comes up with "/usr/local/bin/python" so it seems to be ok?
Since you have the shebang in the file, maybe run it as :
*/15 * * * * /usr/bin/bwmonitor.py
or add
/usr/bin/bwmonitor.py >> /location/of/logfile 2>&1
-
might it be that your have the wrong line endings?
I recently lost a day because my pyton would not run in cron but fine as a script. I had forgotten about the carriage returns.
dos2unix will fix it for you. -
Hey guys,
Thanks for your help. I think it's solved! In the shebang I had
/use/local/bin python
as opposed to
/use/local/bin/python
since then and removing "python" from the crontab entry it seems to be working!
Thanks again.