简体   繁体   English

Linux系统命令无法通过crontab在Perl脚本中使用

[英]Linux system command not working in Perl script via crontab

I have added a script in crontab for every 30 minutes. 我每30分钟在crontab中添加一个脚本。 The line goes as follows: 该行如下:

  */30 * * * * root perl /root/perl.pl

The above script has a execution of system command 'top' and it gets printed in a log file. 上面的脚本执行了系统命令“ top”,并打印在日志文件中。

If I run it manually it runs fine. 如果我手动运行它,则运行良好。 But while running it via crontab, it does not show up the desired results. 但是,通过crontab运行它时,它没有显示出所需的结果。 Please can somebody help me with this. 请有人可以帮我这个忙。 Thank you. 谢谢。


The command in the above perl script is: 上面的perl脚本中的命令是:

 $top = `sudo top`;

The error I am getting is: 我得到的错误是:

sudo: sorry, you must have a tty to run sudo

I changed my command from sudo to visudo. 我将命令从sudo更改为visudo。 But still the problem remains. 但是问题仍然存在。

You should use the full path in cron (and use which perl to find the full path): 您应该在cron中使用完整路径(并使用which perl查找完整路径):

*/30 * * * * root /usr/bin/perl /root/perl.pl 

OR better yet, make the script executable using chmod +x , and add the interpreter to the beginning of the script #!/usr/bin/perl -w and call it directly from cron 或者更好的方法是,使用chmod +x使脚本可执行,然后将解释器添加到脚本#!/usr/bin/perl -w的开头,并直接从cron调用它

*/30 * * * * root /root/perl.pl 

Also if there is a problem in the perl script, you could output the result from cron like this 另外,如果perl脚本中有问题,您可以像这样从cron输出结果

*/30 * * * * root /root/perl.pl > /tmp/myscript.log

You should look into the requiretty setting with regard to visudo. 您应该查看有关visudo的requiretty设置。 Look for a line that reads Defaults requiretty . 寻找一条读为Defaults requiretty You could try commenting it out, but you will be sacrificing some security. 您可以尝试将其注释掉,但是会牺牲一些安全性。 See man sudoers . man sudoers

You could also try running top in batch mode with one iteration: 您还可以尝试通过一次迭代以批处理模式运行top

$top = `sudo top -bn1`;

Batch mode option is for sending output to other programs. 批处理模式选项用于将输出发送到其他程序。

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

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