简体   繁体   English

使用crontab从bash脚本执行php文件作为www-data

[英]Execute php file from bash script as www-data using crontab

I am trying to run a php file every night at a certain time using crontab, however the php needs to be running as a www-data because of the directory permissions. 我试图使用crontab在某个时间每晚运行一个php文件,但由于目录权限,php需要作为www-data运行。 To run it as www-data I am using the root crontab and changing the user in there, like so: 要将其作为www-data运行,我使用root crontab并在那里更改用户,如下所示:

* 20 * * * sudo -u www-data /usr/bin/env TERM=xterm /path/to/dailyProc.sh

dailyProc is as follows dailyProc如下

today=`date +"%d%m%y"`

year=`date +"%y"`

dm=`date +"%m%d"`

`tar -zxf /path/to/input/$today.tgz -C /path/to/output`

echo "starting data proc"

`/usr/bin/php5 -f /path/to/dataproc.php date=$dm year=$year`

echo "data proc done"

All other commands in dailyProc.sh work but the php doesnt run. dailyProc.sh中的所有其他命令都可以工作,但php不会运行。 The php is using an output buffer and writing it to a file, which works fine calling it from the command line but doesnt work when calling by cron. php正在使用输出缓冲区并将其写入文件,从命令行调用它可以正常工作,但在通过cron调用时不起作用。

I can also definitely run dailyProc.sh from the command line as www-data using 我也可以从命令行运行dailyProc.sh作为www-data using

sudo -u www-data dailyProc.sh

and everything works as expected. 一切都按预期工作。

Is there any reason I would not be able to run this php file in dailyProc.sh using crontab when everything else in it works? 是否有任何原因我无法使用crontab在dailyProc.sh运行此php文件,当其他所有内容工作时?

Cron也可以按用户运行。

crontab -u www-data -e

这对我有用:

* 20 * * * su - www-data -C "/path/to/dailyProc.sh"

You do not need to use su or sudo in a crontab entry, because the 6th column is for the user name anyway. 您不需要在crontab条目中使用susudo ,因为第6列仍然是用户名。 And you don't need to start a terminal, because you won't see it anyway. 而且你不需要启动终端,因为你无论如何都不会看到它。 Hence, the following should do: 因此,以下应该做:

* 20 * * * www-data /path/to/dailyProc.sh

The Syntax error: word unexpected… you mentioned in a comment appears to be inside your code. Syntax error: word unexpected…您在评论中提到的似乎在您的代码中。 Try running the script from the command line and start debugging from there. 尝试从命令行运行脚本并从那里开始调试。

To do this I used curl inside dailyProc.sh 为此,我在dailyProc.sh中使用了curl

today=`date +"%d%m%y"`

year=`date +"%y"`

dm=`date +"%m%d"`

`tar -zxf /path/to/input/$today.tgz -C /path/to/output`

echo "starting data proc"

`/usr/bin/curl "myserver.com/dataproc.php?date=$dm?year=$year"`

echo "data proc done"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM