TypeError: 'str' object is not callable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Charlie of Bolton
    New Member
    • Mar 2007
    • 32

    TypeError: 'str' object is not callable

    Hi, everybody,

    Did work hard on this one, as I`m a newbies...
    I did write the entire below script...
    This script is suppose to ping:

    a primary IP (only one), (entered manually w raw-input)
    and than
    secondaries IP ( less than 10), (entered manually w raw-input)

    after entering the IPsssss....

    the ping command does ping the primary, if the primary loss packets average is more than 2% than it goes to a files called 'myprimarylogs. xls'
    and start to ping the secondaries IP,
    and if the secondaries if more than 2 % than goes to the same above file called: 'myprimarylogs. xls'

    once counter finish (after 2 count) than print e-mail.

    Is someone can provide my suggestion,

    I always get this error msg :

    Code:
    Traceback (most recent call last):
      File "E:\Carl Python\21 Octo 2007\PRIMARYandSECONDARY.txt", line 70, in <module>
        ipAddress(0)
      File "E:\Carl Python\21 Octo 2007\PRIMARYandSECONDARY.txt", line 54, in ipAddress
        ipAddress(i+1)
    TypeError: 'str' object is not callable

    Here is my code:

    Code:
    import re
    import time 
    import thread 
    import os
    import sys
    
    f=open('c:/tmp/primaryip.xls','w')
    f.close()
    
    g=open('c:/tmp/workfile.txt','w')
    g.close()
    
    h=open('c:/tmp/myprimarylogs.xls','w')
    h.close()
    
    j=open('c:/tmp/secip.xls','w')
    j.close()
    
    def validIP(ipAddress): 
        ipRegex = r"^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$" 
        re_ip = re.compile(ipRegex) 
        return re_ip.match(ipAddress)
    
    def validIP1(ipAddress1): 
        ipRegex = r"^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$" 
        re_ip = re.compile(ipRegex) 
        return re_ip.match(ipAddress1)
    
    print
    print time.asctime()
    print
    print   (' Ctrl+C to EXIT')
    print
    
    
    def ipAddress1(i):
     ipAddress1 = raw_input("# Enter SECONDARY IP: ")
     if i<=10:
     #if validIP1(ipAddress1 and i<=10): ##########################
            f=open('c:/tmp/secip.xls', 'a+')
            f.write(ipAddress1+"\n")######################
            f.close()
            ipAddress1(i+1)
            anotherip()
     if i>10:
            ping()#######################
     else: 
            print "Wrong syntax"
            ipAddress1(i)#########################
    
    def ipAddress(i):
     ipAddress = raw_input("# Enter Primary IP: ")
     if i<1 :
            ipAddress(i+1)
            print i
            f=open('c:/tmp/primaryip.xls', 'a+')
            f.write(ipAddress+"\n")##########################
            f.close()
            #print f
            #time.sleep(3)
            #print ('Press Enter to Start')
            
     if i>1 :
            ipAddress1(i)
            
     else:
            print "Wrong syntax"
            ipAddress1()
    
    ipAddress(0)
    
    
    
    def anotherip():
        anotherip= raw_input("# Enter another IP? Y/N: " )
        if anotherip.upper() == 'Y':
            ipAddress1()##################
        if anotherip.upper() == 'N':
            ping()##################
        else:
             print ('bye!')
             
    
    def ping(i):
        print i
        if i<=2:
             pingaling =os.popen("ping %s" %(ipAddress),"r")
             results = pingaling.read()
             print results
             for result in results:
              for line in results:
            #os.remove("c:/tmp/workfile.txt")
               g=open('c:/tmp/workfile.txt', 'a+')
               g.write(line+"\n")
               g.close()
               ping(i+1)
               ping1()
        if i>2:
               filter()
    
    def ping1(i):
        ###results1=[]##########################
        z= len(ipAddress1)
        print z   
        while i==z :
             pingaling1 =os.popen("ping %s" %(ipAddress1),"r")
             #####next IP in ipAddress1 or secip.xls
             results1 = pingaling1.read()
             print results1
             for result in results1:
              for line in results1:
            #os.remove("c:/tmp/workfile.txt")
               g=open('c:/tmp/workfile.txt', 'a+')
               g.write(line+"\n")
               g.close()
               ping1(i+1)
               ping1()
        else:
            ping()
             
    def filter(): 
             for line in open("c:/tmp/workfile.txt"): 
              s = 0
              e = 0
              loss_num = 0 # Initialize it
              if line.startswith("Ping statistics for"):
                 ip=line.split()[-1][:-1]
              if line.find("(")!=-1:
                 s=line.index("(")
                 e=line.index(")")
                 loss=line[s+1:e].replace("loss","")
                 print 'loss = ' + loss + ip
                 loss_num = loss.strip() # remove spaces if any
                 loss_num = loss_num.strip('%') # remove the % sign from loss       
                 print 'number = ' + loss_num
              try:
                    loss_num = float(loss_num) # change it into a number
                    if loss_num >= 2 :
                     output_line = loss + ',' + "'" + ip + "'" + "\n"
                     s=open('myprimarylogs.xls', 'a+')
                     #s=open('c:/tmp/myprimarylogs.cvs', 'a+')
                     s.write(output_line+"\n")####################
                     #s.write(line+"\n")
                     s.close()
                     ####################################### 
              except:
                     loss_num = ''
                     mail()
    
    def mail():
             #need to carry on, here, this is the end of PING. 
             print('Do you want to Email?')
             time.sleep(2)
             sys.exit()
  • KaezarRex
    New Member
    • Sep 2007
    • 52

    #2
    Originally posted by Charlie of Bolton
    Hi, everybody,

    Did work hard on this one, as I`m a newbies...
    I did write the entire below script...
    This script is suppose to ping:

    a primary IP (only one), (entered manually w raw-input)
    and than
    secondaries IP ( less than 10), (entered manually w raw-input)

    after entering the IPsssss....

    the ping command does ping the primary, if the primary loss packets average is more than 2% than it goes to a files called 'myprimarylogs. xls'
    and start to ping the secondaries IP,
    and if the secondaries if more than 2 % than goes to the same above file called: 'myprimarylogs. xls'

    once counter finish (after 2 count) than print e-mail.

    Is someone can provide my suggestion,

    I always get this error msg :

    Code:
    Traceback (most recent call last):
      File "E:\Carl Python\21 Octo 2007\PRIMARYandSECONDARY.txt", line 70, in <module>
        ipAddress(0)
      File "E:\Carl Python\21 Octo 2007\PRIMARYandSECONDARY.txt", line 54, in ipAddress
        ipAddress(i+1)
    TypeError: 'str' object is not callable
    Try renaming the function "ipAddress" . I think having the variable "ipAddress" inside a function with the same name is causing the error.

    Comment

    • KaezarRex
      New Member
      • Sep 2007
      • 52

      #3
      On second thought, having a variable anywhere in the script with the same name as a function is probably a bad idea.

      Comment

      • Charlie of Bolton
        New Member
        • Mar 2007
        • 32

        #4
        Hi,

        I`m exhausted, is someone can assist me,
        I did change as your previous comments, but now, I have
        the following:

        Once I entered the following in python idle:

        Code:
         Ctrl+C to EXIT
        
        # Enter Primary IP: 3.3.3.3
        
        # Enter SECONDARY IP: 2.3.3.3
        # Enter another IP? Y/N: n
        
        
        Wrong syntax

        Here is my error msg:

        Code:
        Traceback (most recent call last):
          File "E:\Carl Python\22 Octo 2007\testPRIMARYandSECONDARY.txt", line 159, in <module>
            ipAddress(1)
          File "E:\Carl Python\22 Octo 2007\testPRIMARYandSECONDARY.txt", line 63, in ipAddress
            ipAddress1(1)
          File "E:\Carl Python\22 Octo 2007\testPRIMARYandSECONDARY.txt", line 50, in ipAddress1
            ipAdd1(1)#########################
        TypeError: 'str' object is not callable


        and here is the script:

        Code:
        import re
        import time 
        import thread 
        import os
        import sys
        
        f=open('c:/tmp/primaryip.xls','w')
        f.close()
        
        g=open('c:/tmp/workfile.txt','w')
        g.close()
        
        h=open('c:/tmp/myprimarylogs.xls','w')
        h.close()
        
        j=open('c:/tmp/secip.xls','w')
        j.close()
        
        
        
        k = 1
        i = 1
        l = 1
        m = 1
        
        def validIP(ipAdd): 
            ipRegex = r"^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$" 
            re_ip = re.compile(ipRegex) 
            return re_ip.match(ipAdd)
        
        def validIP1(ipAdd1): 
            ipRegex = r"^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$" 
            re_ip = re.compile(ipRegex) 
            return re_ip.match(ipAdd1)
        
        print
        print time.asctime()
        print
        print   (' Ctrl+C to EXIT')
        print
        
        
        
        
        #def ping(l):
        def ping():
           if l<=2:
                 pingaling =os.popen("ping %s" %(ipAdd),"r")
                 results = pingaling.read()
                 print results
                 for result in results:
                  for line in results:
                #os.remove("c:/tmp/workfile.txt")
                   g=open('c:/tmp/workfile.txt', 'a+')
                   g.write(line+"\n")
                   g.close()
                   ping(i+1)
                   ping1(1)
             if l>2:
                   filter()
        
        def ipAddress1(k):
         while validIP1(ipAdd1) and k<2:
          ipAdd1 = raw_input("# Enter SECONDARY IP: ")
          if k<1 and validIP1(ipAdd1):
         #if validIP1(ipAdd1 and i<=3): 
                f=open('c:/tmp/secip.xls', 'a+')
                f.write(ipAdd1+"\n")
                f.close()
                k=k+1
                #ipAddress1(i+1)
                anotherip()
          if k>= 1:
                ping()
          else: 
                print "Wrong syntax"
                ipAddress1(0)
        
        def ipAddress(i):
         ipAdd = raw_input("# Enter Primary IP: ")
         if i<2 and validIP(ipAdd) :
                i=i+1
                print i
                f=open('c:/tmp/primaryip.xls', 'a+')
                f.write(ipAdd+"\n")
                f.close()
                #print f
                #time.sleep(3)
                #print ('Press Enter to Start')
                ipAddress1(0)
                
         else:
                print "Wrong SYNTAXE"
                ipAddress(0)
        
        
        def anotherip():
            anotherip= raw_input("# Enter another IP? Y/N: " )
            if anotherip.upper() == 'Y':
                ipAddress1(0)##################
            if anotherip.upper() == 'N':
                ping()
            else:
                 print ('bye!')
                 sys.exit()
                 
        
        def ping1(m):
            ###results1=[]##########################
            z= len(ipAddress1)
            print z   
            while m==z :
                 pingaling1 =os.popen("ping %s" %(ipAddress1),"r")
                 #####next IP in ipAddress1 or secip.xls
                 results1 = pingaling1.read()
                 print results1
                 for result in results1:
                  for line in results1:
                #os.remove("c:/tmp/workfile.txt")
                   g=open('c:/tmp/workfile.txt', 'a+')
                   g.write(line+"\n")
                   g.close()
                   ping1(i+1)
                   ping1()
            else:
                ping()
                 
        def filter(): 
                 for line in open("c:/tmp/workfile.txt"): 
                  s = 0
                  e = 0
                  loss_num = 0 # Initialize it
                  if line.startswith("Ping statistics for"):
                     ip=line.split()[-1][:-1]
                  if line.find("(")!=-1:
                     s=line.index("(")
                     e=line.index(")")
                     loss=line[s+1:e].replace("loss","")
                     print 'loss = ' + loss + ip
                     loss_num = loss.strip() # remove spaces if any
                     loss_num = loss_num.strip('%') # remove the % sign from loss       
                     print 'number = ' + loss_num
                  try:
                        loss_num = float(loss_num) # change it into a number
                        if loss_num >= 2 :
                         output_line = loss + ',' + "'" + ip + "'" + "\n"
                         s=open('myprimarylogs.xls', 'a+')
                         #s=open('c:/tmp/myprimarylogs.cvs', 'a+')
                         s.write(output_line+"\n")####################
                         #s.write(line+"\n")
                         s.close()
                         ####################################### 
                  except:
                         loss_num = ''
                         mail()
        
        def mail():
            
                 print('Do you want to Email?')
                 time.sleep(2)
                 sys.exit()
          
        
        
        ipAddress(0)
        ipAddress1(0)
        ping()

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          One potential problem I see is inconsistent indentation. I prefer to use 4 spaces for each indentation. What ever you do, be consistent.

          Here is a problem I see:[code=Python]
          def ipAddress1(k):
          while validIP1(ipAdd1 ) and k<2:
          ipAdd1 = raw_input("# Enter SECONDARY IP: ")
          if k<1 and validIP1(ipAdd1 ):[/code]

          One more:[code=Python]def ping():
          if l<=2:
          pingaling =os.popen("ping %s" %(ipAdd),"r")
          results = pingaling.read( )[/code]'ipAdd1' is referenced before assignment.

          Another problem:[code=Python]def ping():
          if l<=2:
          pingaling =os.popen("ping %s" %(ipAdd),"r")
          results = pingaling.read( )
          print results
          for result in results:
          for line in results:
          #os.remove("c:/tmp/workfile.txt")
          g=open('H:/TEMP/temsys/workfile.txt', 'a+')
          g.write(line+"\ n")
          g.close()
          ping(i+1)[/code]'ping()' does not accept arguments.

          Can you explain what you are trying to do with the validated IP addresses? I am having a hard time following the code.

          Comment

          • Charlie of Bolton
            New Member
            • Mar 2007
            • 32

            #6
            hi bvdet ouff, jesus your are there : )

            Ok, here is what I try to do, from the Idle,


            a) enter only ONE IP(Primary) only with a raw_input
            this IP goes to a file called primaryip.xls, defined with ipAddress(i)
            of course the format of the IP is validate with def validIP(ipAdd):


            b) than entered my Secondary IPsssss, let said: no more than 2 IP entered, these IP goes into a file called secip.xls, defined with def ipAddress1(k)

            if the format is not good, is should write: wrong syntaxe and go back to the raw input to start entering again.

            if both (Primary and Secondary IPs) are entered properly,
            than it should start to ping the first IP(Primary) and if this packet lost value is more than 2%, the value(logs) of the Primary IP goes to a file called my primarylogs.txt with the help of workfile.txt(wh ere I put all the entire logs values from the ping). and if the values of all the SECONDARY IP are more than 2%, than it goes below the primary logs withing the same file : primarylogs.txt

            at the end, if it ping 2 times that I need to e-mail (don't need help for this at the moment I prefer focusing on the present script at the moment).

            To answer your questin, the validIP is to make sure people are putting a good syntaxe for the IP ei: 72..2.3.44 is not good but 72.2.3.44 is ok.

            Comment

            • Charlie of Bolton
              New Member
              • Mar 2007
              • 32

              #7
              Hi,

              my question will be easier, it seems
              that I put to much information and people
              does not no where to look at.

              From my Python idle:
              I entered one primary 2.3.6.5,
              and than secondaries IP (9.6.3.1 and 8.9.6.6)
              once I press N to the following question:

              Enter another IP? Y/N
              than it should ping.

              I would like to know how can I ping the IP within the file called:
              'c:/tmp/primaryip.xls'

              loog for this sign: <------------?????????, where I suspect my pbm.




              Code:
              # Enter Primary IP: 2.3.6.5
              
              # Enter SECONDARY IP: 9.6.3.1
              # Enter another IP? Y/N: y
              # Enter SECONDARY IP: 8.9.6.6
              # Enter another IP? Y/N: n
              start to PING     <---------------------------------???????????????????????
              but at the ping level
              I receive this error msg:

              Code:
               File "E:/Carl Python/24 Octo 2007/test1.txt", line 81, in ping
                  pingaling =os.popen("ping %s" %(ipAdd),"r")
              NameError: global name 'ipAdd' is not defined   <------------???????????
              Here is my code:

              Code:
              import re
              import time 
              import thread 
              import os
              import sys
              
              f=open('c:/tmp/primaryip.xls','w')
              f.close()
              
              g=open('c:/tmp/workfile.txt','w')
              g.close()
              
              h=open('c:/tmp/myprimarylogs.xls','w')
              h.close()
              
              j=open('c:/tmp/secip.xls','w')
              j.close()
              
              k = 1
              i = 1
              l = 1
              
              
              def validIP(ipAdd): 
                  ipRegex = r"^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$" 
                  re_ip = re.compile(ipRegex) 
                  return re_ip.match(ipAdd)
              
              def validIP1(ipAdd1): 
                  ipRegex = r"^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$" 
                  re_ip = re.compile(ipRegex) 
                  return re_ip.match(ipAdd1)
              
              print
              print time.asctime()
              print
              print   (' Ctrl+C to EXIT')
              print
              
              
              def ipAddress1(k):
                ipAdd1 = raw_input("# Enter SECONDARY IP: ")
                if validIP1(ipAdd1): #and k<3:
                      f=open('c:/tmp/secip.xls', 'a+')
                      f.write(ipAdd1+"\n")
                      f.close()
                      anotherip()
                else: 
                      print "Wrong syntax"
                      ipAddress1(0)
              
              
              def ipAddress(i):
               ipAdd = raw_input("# Enter Primary IP: ")
               if i<2 and validIP(ipAdd) :
                      i=i+1
                      print i
                      f=open('c:/tmp/primaryip.xls', 'a+')
                      f.write(ipAdd+"\n")
                      f.close()
                      ipAddress1(0)
                      
               else:
                      print "Wrong SYNTAXE"
                      ipAddress(0)
              
              
              def anotherip():
                  anotherip= raw_input("# Enter another IP? Y/N: " )
                  while anotherip.upper() == 'Y':  
                      ipAddress1(0)
                  if anotherip.upper() == 'N':
                      print ('start to PING')
                      ping(0)       #<---------------------------????????????????????????
              
                  else:
                       print ('BYE!, Y/N not selected!')
                       sys.exit()
                           
              
              def ping(l):
                       pingaling =os.popen("ping %s" %(ipAdd),"r")  #<------????????????
                       results = pingaling.read()
                       print results
                       for result in results:
                        for line in results:
                         g=open('c:/tmp/workfile.txt', 'a+')
                         g.write(line+"\n")
                         g.close()
                         
              ipAddress(0)

              Comment

              • bartonc
                Recognized Expert Expert
                • Sep 2006
                • 6478

                #8
                OK. Your IPs are in a file, right? SO:
                [CODE=python]
                def ping(l):
                f=open('c:/tmp/secip.xls', 'a+')
                ipList = ( line.strip() for line in f.readlines())
                f.close()
                for ipAdd in ipList:
                pingaling =os.popen("ping %s" %(ipAdd),"r") #<------????????????
                results = pingaling.read( )
                print results[/CODE]

                Comment

                • ilikepython
                  Recognized Expert Contributor
                  • Feb 2007
                  • 844

                  #9
                  Originally posted by Charlie of Bolton
                  Hi,

                  my question will be easier, it seems
                  that I put to much information and people
                  does not no where to look at.

                  From my Python idle:
                  I entered one primary 2.3.6.5,
                  and than secondaries IP (9.6.3.1 and 8.9.6.6)
                  once I press N to the following question:

                  Enter another IP? Y/N
                  than it should ping.

                  I would like to know how can I ping the IP within the file called:
                  'c:/tmp/primaryip.xls'

                  loog for this sign: <------------?????????, where I suspect my pbm.




                  Code:
                  # Enter Primary IP: 2.3.6.5
                  
                  # Enter SECONDARY IP: 9.6.3.1
                  # Enter another IP? Y/N: y
                  # Enter SECONDARY IP: 8.9.6.6
                  # Enter another IP? Y/N: n
                  start to PING     <---------------------------------???????????????????????
                  but at the ping level
                  I receive this error msg:

                  Code:
                   File "E:/Carl Python/24 Octo 2007/test1.txt", line 81, in ping
                      pingaling =os.popen("ping %s" %(ipAdd),"r")
                  NameError: global name 'ipAdd' is not defined   <------------???????????
                  That means exactly what is says. You only defined ipAdd locally in one of your functions. You either need to pass it in to ping or maybe it's not so good using functions like that. Maybe like this:
                  [code=python]
                  ipAdd = raw_input("Ente r primary IP: ") # you would also validate this
                  secondaryIPS = []
                  while 1:
                  ipAdd2 = raw_input("Ente r secondary IP: ") # again validate this
                  secondaryIPS.ap pend(ipAdd2)
                  user_input = raw_input("Woul d you like to enter another IP address?: ")

                  if user_input.lowe r() == 'n':
                  break


                  print "Start ping"
                  ping(ipAdd) # and pass anything you need in the ping() function.
                  [/code]
                  Also, you might structure that a little bit differently depending on what you are doing.



                  P.S. There is several wierd things in your code. Why do open all those files in the beginning if you close them right after? Why do you have two identical validIP() functions?
                  Last edited by bartonc; Oct 24 '07, 07:51 PM.

                  Comment

                  • bvdet
                    Recognized Expert Specialist
                    • Oct 2006
                    • 2851

                    #10
                    Originally posted by Charlie of Bolton
                    Hi,

                    my question will be easier, it seems
                    that I put to much information and people
                    does not no where to look at.

                    From my Python idle:
                    I entered one primary 2.3.6.5,
                    and than secondaries IP (9.6.3.1 and 8.9.6.6)
                    once I press N to the following question:

                    Enter another IP? Y/N
                    than it should ping.

                    I would like to know how can I ping the IP within the file called:
                    'c:/tmp/primaryip.xls'

                    loog for this sign: <------------?????????, where I suspect my pbm.




                    Code:
                    # Enter Primary IP: 2.3.6.5
                    
                    # Enter SECONDARY IP: 9.6.3.1
                    # Enter another IP? Y/N: y
                    # Enter SECONDARY IP: 8.9.6.6
                    # Enter another IP? Y/N: n
                    start to PING     <---------------------------------???????????????????????
                    but at the ping level
                    I receive this error msg:

                    Code:
                     File "E:/Carl Python/24 Octo 2007/test1.txt", line 81, in ping
                        pingaling =os.popen("ping %s" %(ipAdd),"r")
                    NameError: global name 'ipAdd' is not defined   <------------???????????
                    Look back at my post, and you will see two places where I pointed out that ipAdd was referenced before assignment. I don't like global variables, but you could do something like this:[code=Python]def ipAddress1(k):
                    while k<2:
                    global ipAdd1
                    ipAdd1 = raw_input("# Enter SECONDARY IP: ")
                    if k<1 and validIP1(ipAdd1 ):
                    ............... ..
                    [/code]
                    [code=Python]def ipAddress(i):
                    global ipAdd
                    ipAdd = raw_input("# Enter Primary IP: ")
                    if i<2 and validIP(ipAdd) :
                    ............... ......[/code]

                    Comment

                    • bartonc
                      Recognized Expert Expert
                      • Sep 2006
                      • 6478

                      #11
                      Originally posted by bvdet
                      Look back at my post<snip>
                      I think that I nailed it in #8...
                      Our new friend, here, is using a file to store a list of IPs (not globals).

                      Comment

                      • Charlie of Bolton
                        New Member
                        • Mar 2007
                        • 32

                        #12
                        Hi Ilikepython, bvdet and Bartonc,
                        I appreciated your replies a lot.

                        Bartonc,
                        I did try your way first and it worked perfectly,
                        only one think I put the log into a file called workfile.txt
                        but the logs are displayed in vertical not horizontal ?

                        I did removed your readlines to read line but this does not help.


                        Here is my code:

                        Code:
                        def ping(l):
                            f=open('c:/tmp/primaryip.xls', 'a+')
                            ipList = ( line.strip() for line in f.read()) ########################
                            f.close()
                            for ipAdd in ipList:
                                 pingaling =os.popen("ping %s" %(ipAdd),"r")  
                                 results = pingaling.read() ########################
                                 print results
                                 for result in results:
                                  for line in results:
                                   g=open('c:/tmp/workfile.txt', 'a+')
                                   g.write(line+"\n")
                                   g.close()
                            s=open('c:/tmp/secip.xls', 'a+')
                            ipList1 = ( line.strip() for line in s.read())########################
                            s.close()
                            for ipAdd1 in ipList1:
                                 pingaling =os.popen("ping %s" %(ipAdd1),"r")  
                                 results = pingaling.read()########################
                                 print results
                                 for result in results:
                                  for line in results:
                                    g=open('c:/tmp/workfile.txt', 'a+')
                                    g.write(line+"\n")
                                    g.close()
                            filter(0)

                        Comment

                        • bvdet
                          Recognized Expert Specialist
                          • Oct 2006
                          • 2851

                          #13
                          Originally posted by bartonc
                          I think that I nailed it in #8...
                          I think you did also. I have added to what you did. I hope this will help the OP.
                          [code=Python]# imports
                          def ping(*fnames):
                          g = open(fnames[0], 'w')
                          for fn in fnames[1:]:
                          f=open(fn, 'r')
                          ipList = [line.strip() for line in f.readlines()]
                          f.close()
                          resList = []
                          for ipAdd in ipList:
                          pingaling =os.popen("ping %s" %(ipAdd),"r")
                          resList.append( pingaling.read( ))
                          g.write('/n'.join(resList ))
                          g.close()

                          def get_IPs(fnP, fnS):
                          # get a primary IP address and write it to file fnP
                          while True:
                          ipAddP = raw_input("# Enter Primary IP: ")
                          if validIP(ipAddP) :
                          f = open(fnP, 'w')
                          f.write(ipAddP + "\n")
                          f.close()
                          break
                          else:
                          print "Invalid IP."

                          ipList = []
                          # get a list if secondary IP addresses and write them to file fnS
                          while True:
                          while True:
                          ipAddS = raw_input("# Enter Secondary IP: ")
                          if validIP(ipAddS) :
                          ipList.append(i pAddS)
                          break
                          else:
                          print "Invalid IP"
                          s = raw_input("# Enter another IP? Y/N: " )
                          if s.upper() == "N":
                          f = open(fnS, 'w')
                          f.write('\n'.jo in(ipList))
                          f.close()
                          break

                          def read_data(fn):
                          f = open(fn)
                          for line in f:
                          if line.strip():
                          print line.strip()
                          f.close()

                          fnP = 'primaryip.txt'
                          fnS = 'secip.txt'
                          fnW = 'workfile.txt'

                          get_IPs(fnP, fnS)
                          ping(fnW, fnP, fnS)
                          read_data(fnW)[/code]Note that filter() is a built-in Python function.

                          Comment

                          • bartonc
                            Recognized Expert Expert
                            • Sep 2006
                            • 6478

                            #14
                            Originally posted by bvdet
                            I think you did also. I have added to what you did. I hope this will help the OP.
                            Great fun! I really enjoy tinkering with these kinds of things. Just wish that I had more time to do so.

                            Comment

                            • Charlie of Bolton
                              New Member
                              • Mar 2007
                              • 32

                              #15
                              Hi bvdet ,

                              Tks so much for this piece of art : )
                              now I have the logs into workfile.xls
                              but I have 2 problems ;

                              1) I would the secondary to be ping only if primary as more than 2% packets lost because the way you made the script, it ping the primary and than the secondary without condition...

                              2) I put the filter as def fil(): but does not want to put the logs into a file called :
                              myprimarylogs.x ls


                              [code=python]

                              def ping(*fnames):
                              g = open(fnames[0], 'w')
                              for fn in fnames[1:]:
                              f=open(fn, 'r')
                              ipList = [line.strip() for line in f.readlines()]
                              f.close()
                              resList = []
                              for ipAdd in ipList:
                              pingaling =os.popen("ping %s" %(ipAdd),"r")
                              resList.append( pingaling.read( ))
                              g.write('/n'.join(resList ))
                              g.close()

                              def get_IPs(fnP, fnS):
                              # get a primary IP address and write it to file fnP
                              while True:
                              ipAddP = raw_input("# Enter Primary IP: ")
                              if validIP(ipAddP) :
                              f = open(fnP, 'w')
                              f.write(ipAddP + "\n")
                              f.close()
                              break
                              else:
                              print "Invalid IP."

                              ipList = []
                              # get a list if secondary IP addresses and write them to file fnS
                              while True:
                              while True:
                              ipAddS = raw_input("# Enter Secondary IP: ")
                              if validIP(ipAddS) :
                              ipList.append(i pAddS)
                              break
                              else:
                              print "Invalid IP"
                              s = raw_input("# Enter another IP? Y/N: " )
                              if s.upper() == "N":
                              f = open(fnS, 'w')
                              f.write('\n'.jo in(ipList))
                              f.close()
                              break

                              def read_data(fn):
                              f = open(fn)
                              for line in f:
                              if line.strip():
                              print line.strip()


                              f.close()

                              def fil():
                              for line in open("c:/tmp/workfile.txt"):
                              s = 0
                              e = 0
                              loss_num = 0 # Initialize it
                              if line.startswith ("Ping statistics for"):
                              ip=line.split()[-1][:-1]
                              if line.find("(")! =-1:
                              s=line.index("( ")
                              e=line.index(") ")
                              loss=line[s+1:e].replace("loss" ,"")
                              print 'loss = ' + loss + ip
                              loss_num = loss.strip() # remove spaces if any
                              loss_num = loss_num.strip( '%') # remove the % sign from loss
                              print 'number = ' + loss_num
                              try:
                              loss_num = float(loss_num) # change it into a number
                              if loss_num >= 2 :
                              output_line = loss + ',' + "'" + ip + "'" + "\n"
                              s=open('myprima rylogs.xls', 'a+')
                              s.write(line+"\ n")
                              s.close()
                              ############### ############### #########
                              except:
                              loss_num = ''
                              mail()


                              fnP = 'c:/tmp/primaryip.xls'
                              fnS = 'c:/tmp/secip.xls'
                              fnW = 'c:/tmp/workfile.txt'

                              get_IPs(fnP, fnS)
                              ping(fnW, fnP, fnS)
                              read_data(fnW)
                              fil()


                              [/code]
                              Last edited by bartonc; Oct 25 '07, 05:31 PM.

                              Comment

                              Working...