June 10, 2009

Check for a Running Process on a Windows Machine

This is a quick and dirty method to check for a running process on a windows machine using Ruby.

require 'win32ole'
require 'net/smtp'
require 'yaml'

def send_email(message) begin msg = <<END_OF_MESSAGE From: #{$from_alias} <#{$from}> To: #{$to_alias} <#{$to}> Subject: #{$subject}

{message}

END_OF_MESSAGE

Net::SMTP.start(&#39;smtp.company.com&#39;) do |smtp|
  smtp.send_message msg, $from, $to
end

rescue => error puts "Exception: #{error}" end end

$from_alias = "Email Alias" $from = "processWatcher@company.com" $subject = "Process Error" $to_alias = "Email Alias" $to = "alerts@company.com"

Server list

$proc = ["Server1", "Server2"]

$proc.each { |record| runningProc = false begin wmi = WIN32OLE.connect("winmgmts://#{record}") processes = wmi.ExecQuery("select * from win32_process") rescue => error puts "Exception: #{error}" end for process in processes do if (process.Name == "SampleProcess.exe") puts "Server: #{record} Name: #{process.Name}" runningProc = true end end

if runningProc puts "Process on #{record} not running as of #{Time.now}. Please check the server." send_email("Process on #{record} not running as of #{Time.now}. Please check the server.") end }

begin File.copy(line.strip, root + templine.strip) rescue => error puts "Error Copying File: Exception: #{error}" error end