Friday, January 4, 2013

Testing host connectivity in WLST

Excellent post on all the possible ways to invoke a OS command in Python/WLST

Since in WLST we don't have the option to use "subprocess" (please Oracle there is no need to upgrade WLST to more recent versions of Python, you could sprain an ankle doing that and it's too dangerous), we must use os.popen(command).

Problem with popen is that stderr is not captured, so I found it easier to redirect stderr to stdout

import os

def pingHost(hostname):
    cmd = 'ping -c 4 ' + hostname + ' 2>&1'
    success = False
    result = ''
    for line in os.popen(cmd).readlines():
        result = result + line  
        if "4 packets transmitted, 4 received" in line:
            success = True
    return success, result 

To test the actual connection, we should use a socket Since I don't have netcat or nmap, I am using plain old stinky telnet.
export HOST=''
export PORT=1522
sleep 5 | telnet $HOST $PORT
this will ensure that the process will be terminated (no hanging, no need to inject a CTRL-] and quit via expect) within 5 seconds.

this will return 1 if connection was successful, 0 otherwise:
sleep 5 | telnet $HOST $PORT | grep -v "Connection refused" | grep "Connected to" | grep -v grep | wc -l

The alternative (faster, no need for timeouts) is using Python sockets:

import socket
host = ''
port = 1522

so this function works very well:
import socket

def connectToHost(hostname, port):
        connect=s.connect((hostname, int(port)))
        return True
        return False

Make sure you cast port into a int, otherwise you will get the infamous "Address must be a tuple of (hostname, port)" error.

No comments: