# encoding: utf-8
module Monitoring
class Monitoring
@@url = ['http://qyapp.com/', 'http://qyapp.cn','http://qyapp.com/index.html','http://qyapp.cn/index.html']
@@from = "用于发邮件的邮箱"
@@to = ["shpwang_qiyun@hotmail.com", "yshli_qiyun@hotmail.com","lbherd_qiyun@hotmail.com","ahtest@foxmail.com"]
@@email_smtp = "smtp.126.com"
@@email_domain = "126.com"
@@email_password = "发信邮箱密码"
@@file=""
@@run_time;
# 启动
def run()
# i = 10
# 10.times(){ |i|
begin
puts Time.now
sleep 5
@@url.each do |url|
unless monitoring(url)
log(:failed, url)
email(" #{run_time} | #{url} | this web filed.")
else
log(:ok,url)
end
end
end while true
# }
end
# 日志
def log(status,url)
if (status==:failed)
message = "#{run_time} | 网页不能正常访问 |url => #{url} \t .????????????????"
else
message = "#{run_time} | 网页可以正常访问 |url => #{url} \t "
end
write message
end
# 创建日志文件
def create_log_file()
file_name = Time.now.strftime("%Y_%m_%d_log.log")
unless (Dir.exist?("./logs"))
Dir::mkdir "./logs"
end
if (File.exist?("./logs/#{file_name}"))
@@file = File.open("./logs/#{file_name}", "a")
else
@@file = File.new("./logs/#{file_name}", "a")
end
end
# 写文件
def write(str)
create_log_file()
@@file.puts str
@@file.close
end
# 时间
def run_time()
run_time = Time.now
run_time
end
# 出错邮件通知
def email(content)
require "net/smtp"
create_log_file()
@@file.puts "\n================= 发送邮件给以下人员 ================="
sendmessage = "From: qiyun<#{@@from}>
Subject: monitor web #{run_time}\n\n #{content}"
smtp = Net::SMTP.start(@@email_smtp, 25, @@email_domain, @@from, @@email_password, :login)
@@to.map do |to|
@@file.puts "#{run_time} | :email to => #{to} \t "
smtp.send_message sendmessage, @@from, to
end
@@file.puts "="*60
@@file.puts "\n"
@@file.close
smtp.finish
end
# 监控web是否正常工作
def monitoring(url)
require 'httpclient'
httpc = HTTPClient.new
begin
httpc.get_content(url)
true
rescue => e
false
end
end
end
end
m = Monitoring::Monitoring.new
m.run
方法比较简陋,这里面用到httpclient,email,file
抛砖引玉吧,希望能给有需要的朋友一点提示.