简体   繁体   English

通过php脚本将文件添加到crontab

[英]Adding file to crontab via php script

I've found at this forum that it is possible to edit crontab like this: 我在这个论坛上发现可以像这样编辑crontab:
a. 一种。 crontab -l > $tmpfile crontab -l> $ tmpfile
b. b。 edit $tmpfile 编辑$ tmpfile
c. C。 crontab $tmpfile crontab $ tmpfile
d. d。 rm $tmpfile rm $ tmpfile
So, I'm trying to implement this solution on php: 因此,我正在尝试在php上实现此解决方案:

include('Net/SSH2.php');
$ssh = new Net_SSH2('myhost');
if (!$ssh->login('user', 'password')) 
{
    echo'Login Failed';
}

    $ssh->exec('crontab -l > /var/www/tmp.txt');
    $content=file_get_contents("/var/www/tmp.txt");
    $content.='0 0 1 * * /usr/bin/php /var/www/clearPreviousMonth1.php';
    $file=fopen("/var/www/tmp.txt", "w");
    fputs($file,$content);
    fclose($file);
    $ssh->exec('crontab /var/www/tmp.txt');
    echo $content;

I can see edited content of crontab in my browser and tmp file, but when I use crontab -e it's not changed. 我可以在浏览器和tmp文件中看到crontab的编辑内容,但是当我使用crontab -e时,它没有改变。 What's my mistake? 我怎么了

I had to add new string before the end of file. 我必须在文件结尾之前添加新字符串。 In other case it's not added to crontab. 在其他情况下,它不会添加到crontab中。 changed $content.='0 0 1 * * /usr/bin/php /var/www/clearPreviousMonth1.php'; 已更改$content.='0 0 1 * * /usr/bin/php /var/www/clearPreviousMonth1.php'; to $content.="0 0 1 * * /usr/bin/php /var/www/clearPreviousMonth1.php\\n"; $content.="0 0 1 * * /usr/bin/php /var/www/clearPreviousMonth1.php\\n"; note that it's neccessary to use " instead of ' , because it just will append \\n symbols to last string 请注意,必须使用"代替' ,因为它只会在最后一个字符串后附加\\n符号

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

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