Skip to content

Instantly share code, notes, and snippets.

@Ceasar Ceasar/traffichistory.rb
Last active Aug 29, 2015

Embed
What would you like to do?
#/usr/bin/ruby
require "cgi"
require "base64"
require "openssl"
require "digest/sha1"
require "uri"
require "net/https"
require "rexml/document"
require "time"
#
# Sample request to Alexa Web Information Service
#
if ARGV.length < 4
$stderr.puts "Usage: urlinfo.rb ACCESS_KEY_ID SECRET_ACCESS_KEY site start_date"
exit(-1)
else
access_key_id = ARGV[0]
secret_access_key = ARGV[1]
site = ARGV[2]
start_date = ARGV[3]
end
range = 7
SERVICE_HOST = "awis.amazonaws.com"
# escape str to RFC 3986
def escapeRFC3986(str)
return URI.escape(str,/[^A-Za-z0-9\-_.~]/)
end
action = "TrafficHistory"
responseGroup = "History"
timestamp = ( Time::now ).utc.strftime("%Y-%m-%dT%H:%M:%S.000Z")
query = {
"Action" => action,
"AWSAccessKeyId" => access_key_id,
"Timestamp" => timestamp,
"ResponseGroup" => responseGroup,
"Range" => range,
"SignatureVersion" => 2,
"SignatureMethod" => "HmacSHA1",
"Start" => start_date,
"Url" => site
}
query_str = query.sort.map{|k,v| k + "=" + escapeRFC3986(v.to_s())}.join('&')
sign_str = "GET\n" + SERVICE_HOST + "\n/\n" + query_str
signature = Base64.encode64( OpenSSL::HMAC.digest( OpenSSL::Digest::Digest.new( "sha1" ), secret_access_key, sign_str)).strip
query_str += "&Signature=" + escapeRFC3986(signature)
url = URI.parse("http://" + SERVICE_HOST + "/?" + query_str)
xml = REXML::Document.new( Net::HTTP.get(url) )
puts xml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.