duanchuang1935
2016-02-09 08:01
浏览 74
已采纳

通过PHP调用bash脚本编辑用户crontab

I am attempting to create a user and add an entry to a users crontab (any user on the system) via a PHP script (running on the same server) which calls a bash script.

I have solved the problem about creating a user, this works OK, but the last line in the bash script to add an entry to that new users crontab does not work when called via the PH script. I have confirmed that it does work when run locally.

I have the following PHP script:

<?php
//system("whoami");
chdir('/var/www/html/sandpit/users/');
$user = "test2";
$user=escapeshellarg($user);
$output = shell_exec("./create_user.sh $user");
echo "<pre>$output</pre>";
//echo "<br>ends";
?>

And the content of create_user.sh is :

#!/bin/bash
export user=$1 
sudo /usr/sbin/useradd $user -M
sudo echo "0 1 * * * /root/test.sh" | tee -a /var/spool/cron/crontabs/test2

In the last line I have hardcoded the variable into the actual name 'test2' to deal with one issue at a time, though I know $user to contain 'test2' because it correctly creates the user.

I have added these line to /etc/sudoers:

www-data ALL=(ALL:ALL) ALL
www-data ALL=(ALL) NOPASSWD: ALL

So my question is, why does the last line to edit the users crontab work when run locally (as root) but not run when called via the script? I assume that it is a permissions issue as I know the command line to work correctly as it runs manually.

Any help would be appreciated. Thanks.

图片转代码服务由CSDN问答提供 功能建议

我正在尝试创建用户并通过一个用户crontab(系统上的任何用户)添加一个条目 调用bash脚本的PHP脚本(在同一服务器上运行)。

我已经解决了创建用户的问题,这个工作正常,但是bash脚本中的最后一行要添加 通过PH脚本调用时,新用户crontab的条目不起作用。 我已经确认它在本地运行时确实有效。

我有以下PHP脚本:

 &lt;?php 
 /  / system(“whoami”); 
chdir('/ var / www / html / sandpit / users /'); 
 $ user =“test2”; 
 $ user = escapeshellarg($ user); 
 $ output  = shell_exec(“./ create_user.sh $ user”); 
echo“&lt; pre&gt; $ output&lt; / pre&gt;”; 
 // echo“&lt; br&gt; ends”; 
?&gt; 
 <  / code>  
 
 

create_user.sh的内容是:

 #!/ bin / bash 
export user = $ 1 
sudo  / usr / sbin / useradd $ user -M 
sudo echo“0 1 * * * /root/test.sh”|  tee -a / var / spool / cron / crontabs / test2 
   
 
 

在最后一行中,我将变量硬编码为实际名称'test2'以处理一个 虽然我知道$ user包含'test2',因为它正确创建了用户。

我已将这些行添加到/ etc / sudoers:

  www-data ALL =(ALL:ALL)ALL 
 -www ALL =(ALL)NOPASSWD:ALL 
   
 
 

所以我的 问题是,为什么编辑用户crontab的最后一行在本地运行时(以root身份运行)但在通过脚本调用时不运行? 我认为这是一个权限问题,因为我知道命令行在手动运行时正常工作。

任何帮助都将不胜感激。 谢谢。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongpankao6133 2016-02-09 09:13
    已采纳

    You need sudo for tee not for echo. tee is not executed with root privileges.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题