Форум HeroesWorld-а - Показать сообщение отдельно - Программирование
Показать сообщение отдельно
#18
Старый 03.09.2008, 05:22
  #18
^
K0Lb@zzeR
 
Аватар для K0Lb@zzeR
📖
Регистрация: 17.06.2006
Адрес: Хакасия
Сообщения: 406
Отправить сообщение для  K0Lb@zzeR с помощью ICQ
Регистрация: 17.06.2006
Адрес: Хакасия
Сообщения: 406
Отправить сообщение для  K0Lb@zzeR с помощью ICQ
Сообщение
Re: программирование

Доброго времени суток.
slayer of dragons;183769кто-нть оцените а то незнаю фигово иль очень фигово)))
Начало хорошое, мне понравилось.

Внесем немного ясности, в неясности
но пишу обычно на дельфе
Delphi - это не язык програмирования, а инструмент разработки программ на Pascal'е (в частности Object Pascal).

А теперь о том, что я успел "понюхать" в програмировании
Начал с Basic и Pascal (еще в школе), затем Object Pascal, HTML, SQL, PHP.
Сейчас изучаю Perl (для души и для работы пригодилось), вот мой первый скрипт (писал не один, друг помог, за что ему огромное спасибо).
	
use cyrillic qw/upcase win2dos/;
use strict;
use Time::HiRes qw/gettimeofday/;
use Data::Dumper;
use Net::SMTP;
use Net::POP3;
use warnings;
use subs qw/load_config mail_auth send_mail read_file write_log write_noping/;
my $debug = 1;
my $config = load_config;
my $offline_text = read_file('offline.txt');
my $online_text = read_file('online.txt');
my $err = "Can't Ping Host";
my @hosts;
#foreach my $host_str (@{$config->{hosts}})
#{
#    my $host = {};
#    $host_str =~ /^\s*(.*?)\s*\=\s*(.*)\s*$/;
#    $host->{descr} = $1;
#    $host->{adres} = $2;
#    $host->{state} = 'online';
#    $host->{fromtime} = gettimeofday();
#    $host->{oldstate} = 0;
#    push @hosts, $host;
#}
foreach my $host_str (@{$config->{hosts}})
{
    my $host = {};
    $host_str =~ /^\s*(.*?)\s*\=\s*(.*)\s*$/;
    $host->{descr} = $1;
    $host->{adres} = $2;
    my $result = "$err $host->{descr} ($host->{adres})";
    my $tm = gettimeofday();
    my $ping = qx/ping $host->{adres} -n 1/;
    $tm = gettimeofday() - $tm;
    foreach (split "\x0a", $ping)
    {
        if(/^.*?[\=\<\>]+.*?[\=\<\>]+(\d+)/)
        {
            $result = sprintf ("Ping to %s (%s) is %s", $host->{descr}, $host->{adres}, $1);
            last;
        }
    }
    my $state = $result =~ /$err/ ? 'offline' : 'online';
    $host->{state} = $state;
    $host->{fromtime} = gettimeofday();
    $host->{oldstate} = 0;
    push @hosts, $host;
}
my $host_descr = '';
my $host_adres = '';
my $namehost = '';
my $date = '';
my @ratio = (1900, 1, 0,0,0,0);
$date = sprintf("%04d-%02d-%02d %02d-%02d-%02d", map{$_+ shift(@ratio)}(localtime(time))[5,4,3,2,1,0]);
my $textlog = "Лог файла начат ${date}\n";
my $namefile = $date;
open (LOGBIGIN, ">>$namefile") || die "Ошибка открытия $namefile: $!";
print LOGBIGIN $textlog;
close (LOGBIGIN);
my $sleep = 30; # В секундах
$date = '';
while(1)
{
    foreach my $host (@hosts)
    {
        my $result = "$err $host->{descr} ($host->{adres})";
        my $tm = gettimeofday();
        my $ping = qx/ping $host->{adres} -n 1/;
        $tm = gettimeofday() - $tm;
        foreach (split "\x0a", $ping)
        {
            if(/^.*?[\=\<\>]+.*?[\=\<\>]+(\d+)/)
            {
                $result = sprintf ("Ping to %s (%s) is %s", $host->{descr}, $host->{adres}, $1);
                last;
            }
        }
        my $state = $result =~ /$err/ ? 'offline' : 'online';
        if ($state ne $host->{state})
        {
            # изменилос состояние
            $host->{oldstate} = gettimeofday()
            if $host->{oldstate} eq 0;
            my $idle = gettimeofday() - $host->{oldstate};
            if ($idle > ($config->{timeout}*60))
            {
                # нужно отправить письма в рассылку
                print win2dos("Изменение статуса на $state для $host->{descr} ($host->{adres})\n");
                eval {mail_auth;};
                print $@ if $@;
                foreach my $rec (@{$config->{recipients}})
                {
                    my $text;
                    if ($state eq 'online')
                    {
                        $text = $online_text;
                    }
                    else
                    {
                        $text = $offline_text;
                    }
                    $host_adres = $host->{adres};
                    $host_descr = $host->{descr};
                    my @ratio_time = (1900, 1, 0,0,0,0);
                    $date = sprintf( "%04d-%02d-%02d %02d:%02d:%02d", map{$_+ shift(@ratio_time)}(localtime(time))[5,4,3,2,1,0]);
                    my $text2 = $text;
                    while($text =~ /\$([\w]+)/g)
                    {
                        my $var = $1;
                        my $val;
                        eval " \$val = \${$var};";
                        #print "$var = $val\n";
                        $text2 =~ s/\$$var/$val/ge;
                    }
                    eval { send_mail($rec, $text2);};
                    print $@ if $@;
                    write_log(sprintf("Change state of Host, last state: %3.2f %s time,", gettimeofday() - $host->{fromtime}, $host->{state})." $result (".sprintf("%0.5f sec", $tm).") $date\n", $namefile);
                }
                $host->{state} = $state;
                $host->{fromtime} = gettimeofday();
                $host->{oldstate} = 0;
            }
        }
        else
        {
            $host->{oldstate} = 0;
        }
        # Если пинг не прошел
        if ($state ne $host->{state})
        {
            if($state eq 'offline')
            {
                $namehost = $host->{adres};
                my @ratio = (1900, 1, 0,0,0,0);
                $date = sprintf( "%04d-%02d-%02d %02d:%02d:%02d", map{$_+ shift(@ratio) }(localtime(time))[5,4,3,2,1,0]);
                write_noping(sprintf("%3.2f %s time,", gettimeofday() - $host->{fromtime}, $host->{state})." $result (".sprintf("%0.5f sec", $tm).") $date\n", $namehost);
            }
        }
        my @ratio = (1900, 1, 0,0,0,0);
        $date = sprintf( "%04d-%02d-%02d %02d:%02d:%02d", map{$_+ shift(@ratio) }(localtime(time))[5,4,3,2,1,0]);
        write_log(sprintf("%3.2f %s time,", gettimeofday() - $host->{fromtime}, $host->{state})." $result (".sprintf("%0.5f sec", $tm).") $date\n", $namefile);
    }
    # write_log("Sleep for $sleep sec (Wait Ping Hosts)\n", $namefile);
    print("Sleep for $sleep sec (Wait Ping Hosts)\n");
    sleep($sleep);
}
sub store_arg
{
    my $config = shift;
    my $arg    = shift;
    if($arg =~ /^\s*(.*?)\s*\=\s*(.*)\s*$/)
    {
        $config->{$1} = $2;
    }
    else
    {
        $config->{$arg} = 1;
    }
}
sub load_config
{
    my $file_name = shift || 'pinger.config';
    my $config = { };
    my $cur_section;
    open (FH, $file_name) || die "can't open config file";
    while (my $line = readline FH)
    {
        next if $line =~ /^\s*\#|^$/;
        $line =~ s/\#.*$//;#$line =~ s/\n//;
        if ($line =~ /^\s*\[(\S*)\]\s*$/)
        {
            $cur_section = $1;
        }
        elsif ($line =~ /^\s*\$\s*$/)
        {
            undef $cur_section;
        }
        else
        {
            if (defined $cur_section)
            {
                push @{$config->{$cur_section}}, $line;
            }
            else
            {
                store_arg($config, $line);
            }
        }
    }
    close FH;
    return $config;
}
sub mail_auth
{
    # авторизация
    # print "$config->{pop3}\n$config->{user} : $config->{pass}\n";
    my $pop = new Net::POP3($config->{pop3}, Timeout => 240, Debug => $debug) || die "$!";
    my $msgs = $pop->login($config->{user}, $config->{pass});
    die "Неверен логин или пароль для ".$config->{pop3} unless defined $msgs;
    $pop->quit();
}
sub send_mail
{
    my $recipient = shift;
    my $text = shift;
    my $smtp = Net::SMTP->new(Host => $config->{smtp},
                                Timeout => 30,
                                Debug   => $debug, ); # Debug => 1 если интересен протокол общения для отладки
    my $dom = $smtp->domain;
    $smtp->mail("$config->{user}\@$dom");
    $smtp->to("$recipient");
    $smtp->data();
    $smtp->datasend("TO: $recipient\n");
    foreach(split /\x0a/, $text)
    {
        $smtp->datasend("$_\n");
    }
    $smtp->dataend();
    $smtp->quit;
}
sub read_file
{
    my $fname = shift;
    open FH, $fname;
    my $text = '';
    while (my $line = <FH>)
    {
        $text .= $line;
    }
    close FH;
    return $text;
}
sub write_log
{
    my $text = shift;
    my $namefile = shift;
    open (w_LOG, ">>$namefile") || die "Ошибка открытия $namefile: $!";
    print w_LOG $text;
    close (w_LOG);
    print (win2dos($text));
}
sub write_noping
{
    my $text = shift;
    my $namehost = shift;
    open (w_PING, ">>$namehost") || die "Ошибка открытия $namehost: $!";
    print w_PING $text;
    close (w_PING);
    # print $text;
} 


Планирую "понюхать" еще Assembler и Java.

С уважением K0Lb@zzeR.
K0Lb@zzeR вне форума
Ответить с цитированием