Last active
June 19, 2018 13:44
-
-
Save xtetsuji/4ade7e35375b799c57ad7ad54cc237ae to your computer and use it in GitHub Desktop.
Very simple HTTP observation script. writen at 2017/06/16 in "Perl Entrance in Tokyo", after party.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
# 2018/06/16 | |
# とても素朴なURL外形監視 | |
use strict; | |
use warnings; | |
use Net::SMTP; | |
use HTTP::Tiny; | |
use Data::Dumper; | |
my $from_address = 'foo@example.com'; | |
my $to_address = 'bar@example.com'; | |
#my $observation_url = "http://www.yahoo.co.jp/"; | |
my $observation_url = "http://www.yahoo.co.jp/not_found"; | |
my $http = HTTP::Tiny->new; | |
my $response = $http->get($observation_url); | |
# ハッシュリファレンスで返されるレスポンスの構造を Data::Dumper で調べる | |
# print Dumper($response); | |
# my $date = $response->{headers}->{date}; | |
# print "Yahoo Server Date is $date\n"; | |
# デーモン的にやるのであれば、原始的なループ | |
# while (1) { | |
# # 処理 | |
# sleep 300; | |
# } | |
# cron 的にやるのであれば単発で | |
if ( $response->{status} eq '200' ) { # == 200 でも良い | |
print "OK\n"; | |
} else { | |
print "$observation_url NG. status is $response->{status}\n"; | |
mailsend( | |
$from_address, | |
$to_address, | |
"$observation_url NG. status is $response->{status}. please check.\n", | |
); | |
} | |
sub mailsend { | |
my ($from, $to, $body) = @_; # この書き方は次回やります | |
my $smtp = Net::SMTP->new('localhost'); | |
$smtp->mail($from); | |
if ($smtp->to($to)) { | |
$smtp->data(); | |
$smtp->datasend("From: $from\n"); | |
$smtp->datasend("To: $to\n"); | |
$smtp->datasend("Subject: observation alert"); | |
$smtp->datasend("\n"); | |
$smtp->datasend("$body\n"); | |
$smtp->dataend(); | |
} else { | |
print "Error: ", $smtp->message(); | |
} | |
$smtp->quit; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment