1

Im trying to use a dictionary to check a given number of servers listed for a particular SQL backup success or fail. My problem so far is when I run this code:

for serverChk in srvrDict['Server']:

it returns the server name as single characters on each new line like:
S
E
R
V
E
R
So in my trial I see this "Error connecting to T to check OS version" where T is the fist character of the servername. I can't seem to put my finger on it and all the searching I've done has lead me to asking. Thanks!

class checkstatus:
#def getServers(self):
    chkbkpstats = csv.reader(file('c://temp//networkerservers.csv'))
    for row in chkbkpstats:
        srvrDict = {}
        srvrDict['Server'] = row[0]
        srvrDict['Instance'] = row[1]
        print srvrDict

for serverChk in srvrDict['Server']:
        try:
            c = wmi.WMI(server)
            for os in c.Win32_OperatingSystem():
                osVer = os.caption
        except:                 
            print 'Error connecting to %s to check OS version' % serverChk

        if '2003' in osVer:
            print 'w2k3'
        if '2008' in osVer:
            print 'w2k8'
5
  • 1
    Could you please show what srvrDict['Server'] is at the beginning of iteration? It looks like it's a single string and thus the iteration occurs over each character. If it's a delimited string of server names, you will need to split the list first. Commented Sep 6, 2012 at 19:23
  • what is the type of srvrDict['Server'], try type(srvrDict['Server']), is it a dict or string? Commented Sep 6, 2012 at 19:27
  • @PlatinumAzure - {'Instance': 'P1RT04', 'Server': 'THP06ASU'} Commented Sep 6, 2012 at 19:33
  • Like I said in my answer your line for serverChk in serverDict['Server'] translates to for serverChk in 'THP06ASU'. You should instead use for instance,server in serverDict.iteritems(). Now server is the value you will want to print out. Or if you just want the values then you can use for server in serverDict.values() Commented Sep 6, 2012 at 19:47
  • Wow, thanks everyone for the quick reply. Im on my way home but will check these out when I get logged back in. (Im new to Python and I thank everyone for your time and help) Commented Sep 6, 2012 at 20:06

3 Answers 3

2

I suppose you have stored a string in your dictionary. So the line for serverChk in srvrDict['Server'] translates to for serverChk in yourSavedString. This is why you are getting individual characters. To access individual dictionary items you should do for k,v in srvrDict.iteritems() where k is the key and v is the value.

Sign up to request clarification or add additional context in comments.

Comments

1

You are overwriting the Server and Instance values in srvrDict each iteration of your loop through chkbkpstats, not actually generating a sequence of data with an entry for each item in your log file as it appears you expect. You need to make that a list containing dictionaries, which you append to each iteration. You are probably looking for something more like:

chkbkpstats = csv.reader(file('c://temp//networkerservers.csv'))
srvrs = []
for for row in chkbkpstats:
    srvrs.append({'Name' : row[0], 'Instance' : row[1]})
for srvr in srvrs:
    try:
        c = wmi.WMI(srvr['Instance'])
    except:                 
        print 'Error connecting to %s to check OS version' % srvr['Name']
    else:
        osVer = c.Win32_OperatingSystem()[0].Caption
        if '2003' in osVer:
            print 'w2k3'
        elif '2008' in osVer:
            print 'w2k8'

5 Comments

This is working so far. When I do a print on srvrs I get a long this of stuff but it returns me the OS ver for each.
Printing srvrs is just going to dump the dict as a string. Not really useful. What else do you need to do with this data set?
after getting the OS version of Win (2k3, 2k8). I will use the results to check a file on the server to see if a backup has failed/inprogress/successful. There is a different location for this file between w2k3 and w2k8. That is why I needed the OS version
So rather then having the print 'w2k3' I would want it to check a dir for a file: c:\temp\instance.ok, c:\temp\instance.err, c:\temp\instance.log. If .ok success, if .err, failed, if .log still running.
Yeah, makes sense. So is your question answered then? :)
1

There are a few problems with your code.

First, you create a new srvrDict each time you go through the first for loop, overwriting the value that was stored in this variable the last time. I think, what you actually intended to do is the following:

srvrDict = {}
for row in chkbkpstats:
    srvrDict[row[0]] = row[1]

Now, srvrDict will contain an entry like {'P1RT04': ['THP06ASU']} for each row in chkbkpstats, mapping server names to lists of instances running on that server.

Then, in the second loop, use for serverChk in srvrDict: to iterate over all the entries in the dictionary. However, I'm not sure where the variable server in c = wmi.WMI(server) comes from. If this is what has been row[1] in the first loop, then you should use srcvDict[serverChk] to retrieve the value from the dictionary.

This way, the whole procedure would look something like this:

chkbkpstats = csv.reader(file('c://temp//networkerservers.csv'))
srvrDict = {}
for row in chkbkpstats:
    name, instance = row[0], row[1]
    if name not in srvrDict:
        srvrDict[name] = []
    srvrDict[name].append(instance)

for server in srvrDict:
    for instance in srvrDict[server]:
        try:
            c = wmi.WMI(instance)
        except:                 
            print 'Error connecting to %s to check OS version' % server
        else:
            osVer = c.Win32_OperatingSystem()[0].caption
            if '2003' in osVer:
                print 'w2k3'
            elif '2008' in osVer:
                print 'w2k8'
            else:
                print 'unknown OS'

PS.: I'm not sure what's the return value of c.Win32_OperatingSystem(). [...] Update: Thanks to sr2222 for pointing this out. Code fixed.

Update: Edited the code to allow for one server hosting multiple instances.

12 Comments

According to the WMI tutorial, all calls to the various interfaces return lists. In the case of Win32_OperatingSystem, the list will always have 1 element.
Should really try to pare down the code in the try: block, especially with a catchall except:.
@sr2222 You are absolutely right, but then again, my code would look 90% like yours, except that I'm using a single dictionary... :-/
Meh, wouldn't offend me. I'd rather SO be a good reference no matter which answer they read than have something be less than it could be for fear of looking plagiarized.
@tobias_k I adjusted my code to reflect your modifications and I ended up with cascading odd results. I'd try and post but it will not fit correctly in this box. What I am looking for is 1 dictionary per server and instance. The number of servers/instances I have vary from day to day. From there I want to check the OS version of Win (2k3, 2k8). I will use the results to check a file on the server to see if a backup has failed/inprogress/successful.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.