Serversup.py

From Nuclear Physics Group Documentation Pages
Revision as of 18:54, 15 June 2010 by Aduston (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

serversup.py is a clever little Python script that pulls down the list of servers from the LDAP Netgroup and pings each one to see if it's available. This won't tell you much, but it's a nice way to quickly see which servers are responding readily to pings.

Code

#!/usr/bin/env python

import ldap, subprocess

# Values needed for connecting and binding to the LDAP server.
# binding anonymously means that name/credentials field can be blank.   
server = "einstein.unh.edu"
who = ""
cred = ""
# Values needed for the LDAP search to retrieve the servers netgroup.
base = "ou=Netgroup,dc=physics,dc=unh,dc=edu"
scope = ldap.SCOPE_SUBTREE
filter = '(cn=servers)'
attributes = None

def get_servers():
    """
        Connect to the LDAP server and get the servers netgroup list.
        Parse the output from LDAP and return a list of hostnames.
    """
    # Initialize an empty list for return data.
    hostnames = []
    try:
        #Open a connection to LDAP server
        l = ldap.open(server)
        l.simple_bind_s(who, cred)
        
        #Search for the servers netgroup
        result = l.search_s(base, scope, filter, attributes)
        
        #Close connection to the LDAP server
        l.unbind()
    
    except ldap.LDAPError, error_message:
        print "Could not connect to LDAP Server: %s" % error_message

    # Try/except because something unexpected may happen with the output.
    try:
        # The search gets us the right information, but for some reason the 
        # hostnames are in a list buried inside a dictionary, inside a tuple,
        # inside another list. Doing the following will get us that list, and 
        # after stripping off unnecessary characters we get a nice neat list 
        # of hostnames.
        list = result[0][1]["nisNetgroupTriple"]
        hostnames  = [i.strip("(").strip(",-,)") for i in list]
    except error_message:
        print "Something bad happened: %s" % error_message

    return hostnames 

def ping_hosts():
    """
    Go through each host in the list from LDAP and send it one ping.
    If that packet doesn't come back successfully we know something
    weird is going on. 
    """
    for host in get_servers():
        command = "ping -c 1 %s " % host  
        print "Pinging %s..." % host
        status = subprocess.call(command, shell=True, 
                                 stdout=open('/dev/null', 'w'), 
                                 stderr=subprocess.STDOUT) 
        if status == 0:
            print "%s is up.\n" % host
        else:
            print "%s is DOWN.\n" % host

if __name__ == "__main__":
    print ""
    ping_hosts()