Sample Ruby Script for accessing RESTful Web Services

This topic was edited by a BMC Contributor and has not been approved.  More information.

The following script was created as an example of using a POST command to execute a BladeLogic Job, and then monitoring the status until the job is complete.

Figure 1: Screenshot showing execution of script, starting a job, monitoring it, and reporting on the status

Setting up the SSL connection

BladeLogic uses self-signed certificates, and these certificates need to be referred to in the script.

The first step is to ensure that a host name (not an IP Address) is used to refer to the application server, and that name is the same as the host name of the application server. This is because the application server's self-signed certificate has the host name inside it.

Now, use openssl to query the self-signed certificate from the application server:

Query BladeLogic self-signed certificate
D:\mjeffery>openssl s_client -connect bl-appserver:9843

This returns SSL information about the application server, including the self-signed certificate:

Example of SSL output connecting to an application server
CONNECTED(00000003)
...
-----BEGIN CERTIFICATE-----
MIICqjCCAZKgAwIBAgIGATpvNgCfMA0GCSqGSIb3DQEBBQUAMBcxFTATBgNVBAMT
DEJMLUFQUFNFUlZFUjAeFw0xMjEwMTYxNDUyMjBaFw0xNTEwMTcxNDUyMjBaMBcx
FTATBgNVBAMTDEJMLUFQUFNFUlZFUjCCASAwDQYJKoZIhvcNAQEBBQADggENADCC
AQgCggEBAM5dkHR0NvbfIxrbArbUbWa/JzJlv9LAkaqeTToyAKBtLO6m/22BUi60
QO3UcZ/33OPmzCaoqWsy/syeLgs/EVqcFh05YKPNI/upsJPtwQbuU4pbfIXJ76JP
B2S3obiLhQMPGO6ijRQLBkKCxTZpTCjiHT8tfeQa2vQkgNtUFauFmwloHw2VFepZ
AyeHDx4mFP+g/gGYg8m+faPtiGov4s7x2Q/bWOoYwtVhkTIwS12fM2bSI5Z4gfrQ
ZMDBHM0gDKyqjsTWPyzTNCNtAPb4IF4gpPOpVSDcjkd93ojNerE7x94r5/Bs9nZE
4mVXH0IZy9RW0kfl9cI/xYtaVGLO6O8CAQMwDQYJKoZIhvcNAQEFBQADggEBADbn
xkaTkPfdJgmdJFF3xWBZzSHC34BoM1ut2YcEbucZvU3/g2DGJFIgLci5Bd654UtC
IVb7/IEwtloRMtzKurAzdvd/hZ8RcTaqdYLBY8RwX+jbUdxMPEzAElrnJYmYQJWe
zzd1fIDhBmJ+IqSJrdNHjlWiD3RarYlWMw0dmqAqencsFrzBnvliQFnAjPszwifG
zaK+Me0SrCoc7ippaPxOoUbJBqh29h3MYV7oXprRAdYL/2mmXkomNjfxgH93jk4c
Cdy1Y3zFQyjCvVojaCJ18Ca6dUPa6oNIU/Xs0BlK4yeuxZMAZOyIw4U9UPXBIlKd
VTttghjUOQTmuSPP/vg=
-----END CERTIFICATE-----
...
---
closed

We only need the text starting with BEGIN CERTIFICATE and END CERTIFICATE, so create a file called something like blappserver.cer.

Next, use openssl to convert this to a blappserver.pem file

Command to create PEM file
openssl x509 -text -in blappserver.cer -out blappserver.pem

The script (Line 52) will then open the blappserver.pem file and use the certificate.

The script
###
# group_name:
#   name: Name of Group
# job_name:
#   name: Name of Job
###
# Flag the script for direct execution
require 'net/http'
require 'net/https'
require 'uri'
require 'rexml/document'
require 'io/console'
# Utility to read in password values without echoing to screen
if STDIN.respond_to?(:noecho)
    def get_password(prompt="Password: ")
        print prompt
        STDIN.noecho(&:gets).chomp
    end
else
    def get_password(prompt="Password: ")
        `read -s -p "#{prompt}" password; echo $password`.chomp
    end
end
# utility to prompt and read value from screen
def get_value(default, prompt)
    print "#{prompt} (#{default}) : "
    result = gets.chomp
    return result.empty? ? default: result
end
# Get values for app server, credentials and job name
host = get_value("bl-appserver", "BladeLogic app server")
username = get_value("BLAdmin", "Username")
password = get_password("Password: ")
role = get_value("BLAdmins", "Role")
authtype = get_value("SRP", "Authorization Type")
group_name = get_value("/Test", "Job Group Name")
job_name = get_value("brpmtest", "Job Name")
# construct authentication string used in URL
auth_string = "?username=#{username}&authType=#{authtype}&password=#{password}&role=#{role}"
# construct URL for execution of the job
url="https://#{host}:9843/group/Jobs#{group_name}/#{job_name}/Operations/execute#{auth_string}"
uri = URI.parse(URI.encode(url))
# Read in certificate from blappserver.pem
cert_store = OpenSSL::X509::Store.new
cert_store.add_file 'blappserver.pem'
# create https connection, using the certificate store.
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.cert_store = cert_store
# POST request to BladeLogic
request = Net::HTTP::Post.new(uri.request_uri)
response = http.request(request)
# Create XML Document object with response body
doc = REXML::Document.new response.body
# Search for error in document.
cl = REXML::XPath.first(doc,'//Error')
if cl then
    # If error, show text
    puts cl.text
else
    # If no error, get Operation Result, which provides the value to interrogate the running job
    cl = REXML::XPath.first(doc,'//OperationResult')
    if cl then
        puts cl.attributes["value"]
        url="https://#{host}:9843#{cl.attributes["value"]}#{auth_string}"
        uri = URI.parse(URI.encode(url))
        status = "unknown"
        # Loop checking Job status every 5 seconds
        until status == "COMPLETE"
            sleep(5)
            # GET request to BladeLogic to get job status
            request = Net::HTTP::Get.new(uri.request_uri)
            response = http.request(request)
            statusd = REXML::Document.new response.body
            # Search for Status in document
            cl = REXML::XPath.first(statusd,'//Status')
            if cl then
                puts cl.attributes["status"]
                status = cl.attributes["status"]
            else
                puts "couldn't find status"
                puts statusd
            end
        end
        # Print results looking at attributes hadErrors and hadWarnings
        puts "The rumours that there were errors are totally " + cl.attributes["hadErrors"]
        puts "The rumours that there were warnings are totally " + cl.attributes["hadWarnings"]
    end
end


Was this page helpful? Yes No Submitting... Thank you

Comments