0

We are having issues with a perl script we run for file count:

#!/usr/bin/perl
    $stat=`sudo lsof | grep username | wc -l`;
    $date=`date '+ %Y/%m/%d-%H:%M:%S'`;
    $exit=`echo $?`;
    if ( $exit == 0 ) {
            print "$date\n Statistic: $stat\n";
            exit 0;
            }

We are able to run this script manually and get the output fine:

# perl test.pl
 2020/07/30-19:17:10
 Statistic: 580

Running as a cronjob */5 * * * * perl /filepath/test.pl >> /filepath/test.txt, it outputs 0:

 2020/07/30-19:20:01
 Statistic: 0

This is running on a RHEL4 machine and we want to run it as a cronjob to append a file to get statistical data.

0

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;
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.