Created
September 16, 2011 20:10
-
-
Save earlonrails/1223022 to your computer and use it in GitHub Desktop.
Check http or https connections with ruby using Net::HTTP or Net::HTTPS
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
require 'uri' | |
require 'net/http' | |
require 'net/https' | |
opts = ARGV.collect{|a| a if a =~ /^(-[a-zA-Z]+)/}.compact | |
url = ARGV - opts | |
use_https = lambda{|http| http.use_ssl = true | |
http.verify_mode = OpenSSL::SSL::VERIFY_NONE} | |
requester = lambda{|http, uri| http.request(Net::HTTP::Get.new(uri.request_uri))} | |
if url.size > 1 | |
puts "Multiple Urls not Supported" | |
exit | |
elsif url.empty? | |
puts "Usage: ruby check_http.rb http://www.my_host.com [-asrhclb]" | |
exit | |
end | |
begin | |
uri = URI.parse(url[0]) | |
rescue | |
puts "Bad url." | |
end | |
begin | |
http = Net::HTTP.new(uri.host, uri.port) | |
use_https.call(http) if uri.scheme == "https" | |
# Options here | |
# -r = response code | |
# -s = response status | |
# -b = respnose body | |
# -c = content type | |
# -l = content length | |
# -h = header | |
# -a username password = basic auth | |
opts.each do |o| | |
case o | |
when /-.*a.*/ | |
a_idx = opts.index("-a") | |
request.basic_auth(opts[a_idx+1], opts[a_idx+2]) | |
response = requester.call(http, uri) | |
puts response.body | |
when /-.*s.*/ | |
response = requester.call(http, uri) | |
puts response.message | |
when /-.*r.*/ | |
response = requester.call(http, uri) | |
puts response.code | |
when /-.*h.*/ | |
response = requester.call(http, uri) | |
puts response.header | |
when /-.*c.*/ | |
response = requester.call(http, uri) | |
puts response.content_type | |
when /-.*l.*/ | |
response = requester.call(http, uri) | |
puts response.content_length | |
when /-.*b.*/ | |
response = requester.call(http, uri) | |
puts response.body | |
when opts.empty? | |
Net::HTTP.get_print(uri) | |
end | |
end | |
rescue | |
puts "Connection failed!" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment