You're right. I'm inexperienced with classes and threading. The example you gave (www.wellho.net) was the same example I used as the basis for my script however I wasn't able to get it to work. I couldn't figure out what the -q parameter is (it's not a valid parameter on the *nix I have access to) and when I gave it an IP address range with reachable and unreachable hosts, it reported them all as alive therefore this example script isn't a good example. I was able to Google for more examples.

I was finally able to get my script to not show duplicate PINGs. I also realized that my script was not PINGing all the hosts in the input file. Here is my latest version:


import os, re, string, sys, threading, time
from threading import Thread
from time import strftime

ms = re.compile("Reply")
rpath = (r"c:\utils\network_ping_devices.txt")

if os.path.exists(r"c:\utils\network_ping_again.txt"):
    rpath = (r"c:\utils\network_ping_again.txt")
wpath = (r"c:\logs\network_ping.out")
tpath =  (r"c:\temp\ping.txt")
if os.path.exists(tpath):
    os.remove(tpath)
temp = open(tpath, "w")
output = open(wpath, "a")
output.write("\n" + "Network PING test started -" + strftime(" %H:%M:%S %x") + "\n")
output.flush()

class PingIT(threading.Thread):
    def __init__(self,rtr):
        Thread.__init__(self)
        self.rtr = rtr

    def run(self):
        pingaf = os.popen('ping -n 1 -w 3000 ' + self.rtr)
        pingas = string.join(pingaf.readlines())
        if ms.search(pingas):
#            print (re.sub('\n','',self.rtr)) + " responded."    #for debugging
            return
        else:
            pingaf = os.popen('ping -n 1 -w 3000 ' + self.rtr)
            pingas = string.join(pingaf.readlines())
            if ms.search(pingas):
#                print (re.sub('\n','',self.rtr)) + " responded."    # for debugging
                return
            else:
                temp.write(re.sub('\n','',self.rtr) + " did not respond.\n")

pinglist = []
for rtr in file(rpath):
    current = PingIT(rtr)
    pinglist.append(current)
    current.start()

for pingle in pinglist:
    pingle.join()

temp.close()
temp = open(tpath, "r")
lines = []
for line in temp:
    lines.append(line.rstrip())
    lines.sort()
for line in lines:
    print >>output, line

output.write("Network PING test completed -" + strftime(" %H:%M:%S %x") + "\n")
output.flush()
output.close()


All the hosts in the input file are sorted alphabetically but my results were output out of order?! (possibly due to latency in PING responses or some latency in the thread joining; not sure of either). I had to do the crude temp output file so that I could sort the results, but it works!! 


On 10/23/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
Chris Hallman wrote:
>
> I made a mistake in my first email..... I meant that I can't get fc to
> write to the file. Here is the error:
>
> Traceback (most recent call last):
>   File "thread_test_ping.py", line 37, in ?
>     output.write(fc + " failures found.\n")
> TypeError: unsupported operand type(s) for +: 'int' and 'str'

This is a pretty easy error to understand. It is saying that you can't add an int and a string. Looking at your code, you are trying to add fc + " failures found.\n". fc is indeed an int. You have to change it to a string to be able to add it to another string. You can do this with the str() function. So the correct statement is
  output.write(str(fc) + " failures found.\n")

>
> I tried the suggestions you made, but I can't get it to work. Is this
> what you meant?:

No, not quite.
>
> #!/usr/bin/env python
>
> #Let us profile code which uses threads
> import os, re, string, thread, threading, time
> from time import strftime
> #from threading import Thread
>
> class PingThread(threading.Thread):
>     def __init__(self, rtr):
>         threading.Thread.__init__(self)
>         self.rtr = rtr

The init method initializes a PingThread. It is passed self as an argument, plus whatever parameters you pass in when you create the PingThread. You call the superclass constructor and save the value of the parameter. So far so good...but this next line is creating a PingThread, it belongs below in your loop.

>         PingThread(rtr).start(rtr)
>
>     def run(self):

Here you should reference self.rtr so you get the value that was stored in the call to __init__(), and similarly for each reference to rtr in the run method.

>         pingaf = os.popen('ping -n 1 -w 3 ' + rtr)
>         pingas = string.join(pingaf.readlines())
>         if ms.search(pingas):
>             print (re.sub('\n','',rtr)) + " responded."    #for debugging
>         else:
>             pingaf = os.popen('ping -n 2 -w 3 ' + rtr)
>             pingas = string.join(pingaf.readlines())
>             if ms.search(pingas):
>                 print (re.sub('\n','',rtr)) + " responded."    # for
> debugging
>             else:
>                 fc=fc+1
>                 output.write(re.sub('\n','',rtr) + " did not respond.\n")
>
> fc = 0    # failure counter
> ms = re.compile("Reply from")
> rpath = (r"c:\temp\py\network_ping_routers.txt")
> if os.path.exists(r"c:\temp\py\network_ping_again.txt"):
>     rpath = (r"c:\temp\py\network_ping_again.txt")
> wpath = (r"c:\temp\py\network_ping.out")
> #os.system(r"c:\tnd\bin\cawto.exe -cat NetNet -n l17aesm1 forward blue
> held Weekly ISDN testing has started -" + strftime(" %H:%M:%S %x") + "\n")
> output = open(wpath, "a")
> output.write("\n" + "\n" + "Network PING test started -" + strftime("
> %H:%M:%S %x") + "\n")
> output.flush()
> threads = []
> for rtr in file(rpath):
>     thread = PingThread()
Here is where you need to call PingThread(rtr) to pass the value of rtr to the constructor.

>     thread.start()
>     threads.append(thread)
> for thread in threads:
>     thread.join()
> print fc    # for debugging
> output.write(fc + " failures found.\n")
> output.write("\n" + "\n" + "Network PING test completed -" + strftime("
> %H:%M:%S %x") + "\n")
> output.close()

I suspect that I am talking over your head and that maybe you are in over your head a bit here. If you don't understand the basics of classes and parameter passing you should spend some time with a tutorial that explains them, for example Alan Gauld's tutorial at
http://www.freenetpages.co.uk/hp/alan.gauld/

There is a brief introduction to threading here. It even uses your problem (pinging multiple servers) as the example.
http://www.wellho.net/solutions/python-python-threads-a-first-example.html

Kent
http://www.kentsjohnson.com

_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to