Страница 1 из 1

Странное поведение perl-скрипта

Добавлено: 2009-02-02 13:16:03
vpupkin
Здравствуйте, уважаемые.
Возникла необходимость периодически менять автоматом пользовательский crontab файл, если оный изменился в папе пользователя.
Для этого был написан скрипт, который сравнивает MD5-хеш пользовательского файла с тем что у него есть в базе.
Если хеш отличается - то происходит установка нового crontab файла.
Вот сам скрипт:

Код: Выделить всё

#!/usr/bin/perl
##### Modifed by lynx
##### require /usr/ports/security/p5-MD5
##### require empty files: crontab2.hash, crontab2.log with grant write crontab-user.

use File::Copy;
use Digest::MD5;
my $checkfile = $ARGV[0];
my $hashfile='/home/scripts/crontab2.hash';
my $in;
my $status = 0;

if (not -f $checkfile) {
    print "File not found: $checkfile\n";
    exit;
}

if (not -f $hashfile) {
    print "HASHFile not found, creating\n";
    open (MD, '>'.$hashfile) or die "Cannot create HASHFile: $hashfile\n";
    close (MD);
}

open (MD, '<'.$hashfile) or die "Cannot open HASHFile: $hashfile\n";
$md5Current = new Digest::MD5;
while ($in=<MD>) {
    chomp $in;
    my ($hash, $file) = split (/ /, $in);
#    print "HASH=$hash, FILE=$file\n";
    if ($file eq $checkfile) {
        if ($md5Current->md5_hex($hashfile) eq $hash) {
#           print "File found and his hash equal!\n";
            $status = 1;
        }
        else {
            print "Files found, but hash differ! Change crontab.\n";
            close (MD);
            installCrontab($checkfile);
            updateHash();
            exit;
        }
    }
}
if ($status == 0) {
    print "Hash for file $checkfile not found, adding... ";
    open (MD, '>>'.$hashfile) or die "Cannot open HASHFile $hashfile for add new hash!\n";
    print MD $md5Current->md5_hex($hashfile)." ".$checkfile."\n";
    close (MD);
    installCrontab($checkfile);
    print "Success!\n"
}

sub installCrontab {
    system("echo [`date`]Changed >> /tmp/ddddd");
    $whoami=`/usr/bin/whoami`;
    $whoami=~s/\n//;
    $tmpfile="/tmp/$whoami-crontab.tmp";
    unlink $tmpfile;
    open(FF, @_[0]);
    open(TMP, '>>'.$tmpfile);
    while (<FF>){
        ##    next if $_=~m/\#/;
        $_=~s/\r//;
        print TMP $_;
    }
    close(TMP);
    close(FF);
    system("/usr/bin/crontab $tmpfile");
    unlink $tmpfile;
    #unlink $filechanged;
}

sub updateHash {
    print "SUB: update hash\n";
    open (MD, '<'.$hashfile) or die "Cannot open HASHFile: $hashfile\n";
    open (MDNew, '>/tmp/crontab2.hash.tmp') or die "Cannot open temp HASHFile: /tmp/crontab2.hash.tmp\n";
    while ($in=<MD>) {
        chomp $in;
        my ($hash, $file) = split (/ /, $in);
        if ($file eq $checkfile) {
            $hash=$md5Current->md5_hex($hashfile);
        }
        print MDNew $hash." ".$file."\n";
        print $hash." ".$file."\n";
    }
    close (MD);
    close (MDNew);
    move ('/tmp/crontab2.hash.tmp', $hashfile) or die "fail to move";
}

Руками из под рута или из под пользователя все отрабатывает на ура, но как только прописывается в кроне - не работает, не могу понять почему.

Вот строчка крона:

Код: Выделить всё

*/1     *       *       *       *       webadmin  /home/scripts/crontab2.pl /home/webadmin/site/cron/crontab 2>&1 >> /home/scripts/crontab2.log
У меня возникло много вопросов по отработке перлового скрипта из-под крона.

1. Почему вот такая конструкция
open (MD, '<'.$hashfile) or die "Cannot open HASHFile: $hashfile\n";
работает везде, т.е. под рутом, пользователем и через крон, а вот такая:
open (MD, "<$hashfile") or die "Cannot open HASHFile: $hashfile\n";
только под рутом и пользователем, но не под кроном.

2. Почему при запуске пользователем и кроном MD5-хеш разные?

И соответственно, как вытекает из всего этого, при запуске из под крона хэп всегда один и тот же и скрипт не отрабатывает как надо.

Помогите пожалуйста, что я упустил?

Re: Странное поведение perl-скрипта

Добавлено: 2009-02-03 23:37:54
ProFTP
многа букфф, понять сложно

для начала хотябы:

Код: Выделить всё

use strict;
вообще-то проанализируйте, и найдите ошибку...

Re: Странное поведение perl-скрипта

Добавлено: 2009-02-04 11:20:42
vpupkin
ProFTP писал(а):многа букфф, понять сложно

для начала хотябы:

Код: Выделить всё

use strict;
вообще-то проанализируйте, и найдите ошибку...
Ошибку с MD5 я нашел, мои кривые руки :) Не ту переменную брал.
Пойду читать про strict