Improving the script might work:
#!/usr/bin/perl
use POSIX qw(strftime);
$user = shift; $outputfile = shift;
$lsof=`lsof 2> /dev/null`;
exit $? unless($? == 0);
$count=0;
foreach(split /\n/, $lsof) {
$count++ if(/$user/);
}
open($fh, ">>$outputfile") or die "Can't append to $outputfile";
print $fh strftime(" %Y/%m/%d-%H:%M:%S\n Statistic: $count\n", localtime);
close $fh;
Which would become this in cron
*/5 * * * * root perl /filepath/test.pl username /filepath/test.txt
Things that were wrong in your case:
- The username field was missing in cron (I use
root
so we don't have to elevate privileges with sudo
)
- Even if there was a username,
sudo
would fail because of a missing password
echo $?
will be the returncode of the echo-command, all other commands are ignored
- Not exactly wrong, but advised against: too much shell code in your perlscript
- Might not be wrong but I think you don't want it: All the warnings of lsof weren't filtered away
If it still doesn't work try switching lsof
by the full path (most likely /usr/bin/lsof
)
Edit: Another problem: your grep
and my regexp will also find lines that contain username
when this string is not meant as a username.
This code is even better:
#!/usr/bin/perl
use POSIX qw(strftime);
$user = shift; $outputfile = shift;
$count=split(/n/,`lsof -u $user 2> /dev/null`);
exit $? unless($?==0);
open($fh, ">>$outputfile") or die "Can't append to $outputfile";
print $fh strftime(" %Y/%m/%d-%H:%M:%S\n Statistic: $count\n", localtime);
close $fh;
sudo
may not like being run without a terminal device - see for example Why does cron silently fail to run sudo stuff in my script?