473,287 Members | 1,463 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

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 :

Expand|Select|Wrap|Line Numbers
  1. Traceback (most recent call last):
  2.   File "E:\Carl Python\21 Octo 2007\PRIMARYandSECONDARY.txt", line 70, in <module>
  3.     ipAddress(0)
  4.   File "E:\Carl Python\21 Octo 2007\PRIMARYandSECONDARY.txt", line 54, in ipAddress
  5.     ipAddress(i+1)
  6. TypeError: 'str' object is not callable
  7.  

Here is my code:

Expand|Select|Wrap|Line Numbers
  1.  
  2. import re
  3. import time 
  4. import thread 
  5. import os
  6. import sys
  7.  
  8. f=open('c:/tmp/primaryip.xls','w')
  9. f.close()
  10.  
  11. g=open('c:/tmp/workfile.txt','w')
  12. g.close()
  13.  
  14. h=open('c:/tmp/myprimarylogs.xls','w')
  15. h.close()
  16.  
  17. j=open('c:/tmp/secip.xls','w')
  18. j.close()
  19.  
  20. def validIP(ipAddress): 
  21.     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])$" 
  22.     re_ip = re.compile(ipRegex) 
  23.     return re_ip.match(ipAddress)
  24.  
  25. def validIP1(ipAddress1): 
  26.     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])$" 
  27.     re_ip = re.compile(ipRegex) 
  28.     return re_ip.match(ipAddress1)
  29.  
  30. print
  31. print time.asctime()
  32. print
  33. print   (' Ctrl+C to EXIT')
  34. print
  35.  
  36.  
  37. def ipAddress1(i):
  38.  ipAddress1 = raw_input("# Enter SECONDARY IP: ")
  39.  if i<=10:
  40.  #if validIP1(ipAddress1 and i<=10): ##########################
  41.         f=open('c:/tmp/secip.xls', 'a+')
  42.         f.write(ipAddress1+"\n")######################
  43.         f.close()
  44.         ipAddress1(i+1)
  45.         anotherip()
  46.  if i>10:
  47.         ping()#######################
  48.  else: 
  49.         print "Wrong syntax"
  50.         ipAddress1(i)#########################
  51.  
  52. def ipAddress(i):
  53.  ipAddress = raw_input("# Enter Primary IP: ")
  54.  if i<1 :
  55.         ipAddress(i+1)
  56.         print i
  57.         f=open('c:/tmp/primaryip.xls', 'a+')
  58.         f.write(ipAddress+"\n")##########################
  59.         f.close()
  60.         #print f
  61.         #time.sleep(3)
  62.         #print ('Press Enter to Start')
  63.  
  64.  if i>1 :
  65.         ipAddress1(i)
  66.  
  67.  else:
  68.         print "Wrong syntax"
  69.         ipAddress1()
  70.  
  71. ipAddress(0)
  72.  
  73.  
  74.  
  75. def anotherip():
  76.     anotherip= raw_input("# Enter another IP? Y/N: " )
  77.     if anotherip.upper() == 'Y':
  78.         ipAddress1()##################
  79.     if anotherip.upper() == 'N':
  80.         ping()##################
  81.     else:
  82.          print ('bye!')
  83.  
  84.  
  85. def ping(i):
  86.     print i
  87.     if i<=2:
  88.          pingaling =os.popen("ping %s" %(ipAddress),"r")
  89.          results = pingaling.read()
  90.          print results
  91.          for result in results:
  92.           for line in results:
  93.         #os.remove("c:/tmp/workfile.txt")
  94.            g=open('c:/tmp/workfile.txt', 'a+')
  95.            g.write(line+"\n")
  96.            g.close()
  97.            ping(i+1)
  98.            ping1()
  99.     if i>2:
  100.            filter()
  101.  
  102. def ping1(i):
  103.     ###results1=[]##########################
  104.     z= len(ipAddress1)
  105.     print z   
  106.     while i==z :
  107.          pingaling1 =os.popen("ping %s" %(ipAddress1),"r")
  108.          #####next IP in ipAddress1 or secip.xls
  109.          results1 = pingaling1.read()
  110.          print results1
  111.          for result in results1:
  112.           for line in results1:
  113.         #os.remove("c:/tmp/workfile.txt")
  114.            g=open('c:/tmp/workfile.txt', 'a+')
  115.            g.write(line+"\n")
  116.            g.close()
  117.            ping1(i+1)
  118.            ping1()
  119.     else:
  120.         ping()
  121.  
  122. def filter(): 
  123.          for line in open("c:/tmp/workfile.txt"): 
  124.           s = 0
  125.           e = 0
  126.           loss_num = 0 # Initialize it
  127.           if line.startswith("Ping statistics for"):
  128.              ip=line.split()[-1][:-1]
  129.           if line.find("(")!=-1:
  130.              s=line.index("(")
  131.              e=line.index(")")
  132.              loss=line[s+1:e].replace("loss","")
  133.              print 'loss = ' + loss + ip
  134.              loss_num = loss.strip() # remove spaces if any
  135.              loss_num = loss_num.strip('%') # remove the % sign from loss       
  136.              print 'number = ' + loss_num
  137.           try:
  138.                 loss_num = float(loss_num) # change it into a number
  139.                 if loss_num >= 2 :
  140.                  output_line = loss + ',' + "'" + ip + "'" + "\n"
  141.                  s=open('myprimarylogs.xls', 'a+')
  142.                  #s=open('c:/tmp/myprimarylogs.cvs', 'a+')
  143.                  s.write(output_line+"\n")####################
  144.                  #s.write(line+"\n")
  145.                  s.close()
  146.                  ####################################### 
  147.           except:
  148.                  loss_num = ''
  149.                  mail()
  150.  
  151. def mail():
  152.          #need to carry on, here, this is the end of PING. 
  153.          print('Do you want to Email?')
  154.          time.sleep(2)
  155.          sys.exit()
  156.  
  157.  
  158.  
Oct 22 '07 #1
18 15712
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 :

Expand|Select|Wrap|Line Numbers
  1. Traceback (most recent call last):
  2.   File "E:\Carl Python\21 Octo 2007\PRIMARYandSECONDARY.txt", line 70, in <module>
  3.     ipAddress(0)
  4.   File "E:\Carl Python\21 Octo 2007\PRIMARYandSECONDARY.txt", line 54, in ipAddress
  5.     ipAddress(i+1)
  6. TypeError: 'str' object is not callable
  7.  
Try renaming the function "ipAddress". I think having the variable "ipAddress" inside a function with the same name is causing the error.
Oct 22 '07 #2
On second thought, having a variable anywhere in the script with the same name as a function is probably a bad idea.
Oct 22 '07 #3
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:

Expand|Select|Wrap|Line Numbers
  1.  
  2.  Ctrl+C to EXIT
  3.  
  4. # Enter Primary IP: 3.3.3.3
  5.  
  6. # Enter SECONDARY IP: 2.3.3.3
  7. # Enter another IP? Y/N: n
  8.  
  9.  
  10. Wrong syntax
  11.  
  12.  

Here is my error msg:

Expand|Select|Wrap|Line Numbers
  1.  
  2. Traceback (most recent call last):
  3.   File "E:\Carl Python\22 Octo 2007\testPRIMARYandSECONDARY.txt", line 159, in <module>
  4.     ipAddress(1)
  5.   File "E:\Carl Python\22 Octo 2007\testPRIMARYandSECONDARY.txt", line 63, in ipAddress
  6.     ipAddress1(1)
  7.   File "E:\Carl Python\22 Octo 2007\testPRIMARYandSECONDARY.txt", line 50, in ipAddress1
  8.     ipAdd1(1)#########################
  9. TypeError: 'str' object is not callable
  10.  
  11.  


and here is the script:

Expand|Select|Wrap|Line Numbers
  1.  
  2. import re
  3. import time 
  4. import thread 
  5. import os
  6. import sys
  7.  
  8. f=open('c:/tmp/primaryip.xls','w')
  9. f.close()
  10.  
  11. g=open('c:/tmp/workfile.txt','w')
  12. g.close()
  13.  
  14. h=open('c:/tmp/myprimarylogs.xls','w')
  15. h.close()
  16.  
  17. j=open('c:/tmp/secip.xls','w')
  18. j.close()
  19.  
  20.  
  21.  
  22. k = 1
  23. i = 1
  24. l = 1
  25. m = 1
  26.  
  27. def validIP(ipAdd): 
  28.     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])$" 
  29.     re_ip = re.compile(ipRegex) 
  30.     return re_ip.match(ipAdd)
  31.  
  32. def validIP1(ipAdd1): 
  33.     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])$" 
  34.     re_ip = re.compile(ipRegex) 
  35.     return re_ip.match(ipAdd1)
  36.  
  37. print
  38. print time.asctime()
  39. print
  40. print   (' Ctrl+C to EXIT')
  41. print
  42.  
  43.  
  44.  
  45.  
  46. #def ping(l):
  47. def ping():
  48.    if l<=2:
  49.          pingaling =os.popen("ping %s" %(ipAdd),"r")
  50.          results = pingaling.read()
  51.          print results
  52.          for result in results:
  53.           for line in results:
  54.         #os.remove("c:/tmp/workfile.txt")
  55.            g=open('c:/tmp/workfile.txt', 'a+')
  56.            g.write(line+"\n")
  57.            g.close()
  58.            ping(i+1)
  59.            ping1(1)
  60.      if l>2:
  61.            filter()
  62.  
  63. def ipAddress1(k):
  64.  while validIP1(ipAdd1) and k<2:
  65.   ipAdd1 = raw_input("# Enter SECONDARY IP: ")
  66.   if k<1 and validIP1(ipAdd1):
  67.  #if validIP1(ipAdd1 and i<=3): 
  68.         f=open('c:/tmp/secip.xls', 'a+')
  69.         f.write(ipAdd1+"\n")
  70.         f.close()
  71.         k=k+1
  72.         #ipAddress1(i+1)
  73.         anotherip()
  74.   if k>= 1:
  75.         ping()
  76.   else: 
  77.         print "Wrong syntax"
  78.         ipAddress1(0)
  79.  
  80. def ipAddress(i):
  81.  ipAdd = raw_input("# Enter Primary IP: ")
  82.  if i<2 and validIP(ipAdd) :
  83.         i=i+1
  84.         print i
  85.         f=open('c:/tmp/primaryip.xls', 'a+')
  86.         f.write(ipAdd+"\n")
  87.         f.close()
  88.         #print f
  89.         #time.sleep(3)
  90.         #print ('Press Enter to Start')
  91.         ipAddress1(0)
  92.  
  93.  else:
  94.         print "Wrong SYNTAXE"
  95.         ipAddress(0)
  96.  
  97.  
  98. def anotherip():
  99.     anotherip= raw_input("# Enter another IP? Y/N: " )
  100.     if anotherip.upper() == 'Y':
  101.         ipAddress1(0)##################
  102.     if anotherip.upper() == 'N':
  103.         ping()
  104.     else:
  105.          print ('bye!')
  106.          sys.exit()
  107.  
  108.  
  109. def ping1(m):
  110.     ###results1=[]##########################
  111.     z= len(ipAddress1)
  112.     print z   
  113.     while m==z :
  114.          pingaling1 =os.popen("ping %s" %(ipAddress1),"r")
  115.          #####next IP in ipAddress1 or secip.xls
  116.          results1 = pingaling1.read()
  117.          print results1
  118.          for result in results1:
  119.           for line in results1:
  120.         #os.remove("c:/tmp/workfile.txt")
  121.            g=open('c:/tmp/workfile.txt', 'a+')
  122.            g.write(line+"\n")
  123.            g.close()
  124.            ping1(i+1)
  125.            ping1()
  126.     else:
  127.         ping()
  128.  
  129. def filter(): 
  130.          for line in open("c:/tmp/workfile.txt"): 
  131.           s = 0
  132.           e = 0
  133.           loss_num = 0 # Initialize it
  134.           if line.startswith("Ping statistics for"):
  135.              ip=line.split()[-1][:-1]
  136.           if line.find("(")!=-1:
  137.              s=line.index("(")
  138.              e=line.index(")")
  139.              loss=line[s+1:e].replace("loss","")
  140.              print 'loss = ' + loss + ip
  141.              loss_num = loss.strip() # remove spaces if any
  142.              loss_num = loss_num.strip('%') # remove the % sign from loss       
  143.              print 'number = ' + loss_num
  144.           try:
  145.                 loss_num = float(loss_num) # change it into a number
  146.                 if loss_num >= 2 :
  147.                  output_line = loss + ',' + "'" + ip + "'" + "\n"
  148.                  s=open('myprimarylogs.xls', 'a+')
  149.                  #s=open('c:/tmp/myprimarylogs.cvs', 'a+')
  150.                  s.write(output_line+"\n")####################
  151.                  #s.write(line+"\n")
  152.                  s.close()
  153.                  ####################################### 
  154.           except:
  155.                  loss_num = ''
  156.                  mail()
  157.  
  158. def mail():
  159.  
  160.          print('Do you want to Email?')
  161.          time.sleep(2)
  162.          sys.exit()
  163.  
  164.  
  165.  
  166. ipAddress(0)
  167. ipAddress1(0)
  168. ping()
  169.  
  170.  
Oct 23 '07 #4
bvdet
2,851 Expert Mod 2GB
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:
Expand|Select|Wrap|Line Numbers
  1. def ipAddress1(k):
  2.  while validIP1(ipAdd1) and k<2:
  3.   ipAdd1 = raw_input("# Enter SECONDARY IP: ")
  4.   if k<1 and validIP1(ipAdd1):
One more:
Expand|Select|Wrap|Line Numbers
  1. def ping():
  2.     if l<=2:
  3.         pingaling =os.popen("ping %s" %(ipAdd),"r")
  4.         results = pingaling.read()
'ipAdd1' is referenced before assignment.

Another problem:
Expand|Select|Wrap|Line Numbers
  1. def ping():
  2.     if l<=2:
  3.         pingaling =os.popen("ping %s" %(ipAdd),"r")
  4.         results = pingaling.read()
  5.         print results
  6.         for result in results:
  7.             for line in results:
  8.             #os.remove("c:/tmp/workfile.txt")
  9.                 g=open('H:/TEMP/temsys/workfile.txt', 'a+')
  10.                 g.write(line+"\n")
  11.                 g.close()
  12.                 ping(i+1)
'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.
Oct 23 '07 #5
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(where 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.
Oct 23 '07 #6
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.




Expand|Select|Wrap|Line Numbers
  1.  
  2. # Enter Primary IP: 2.3.6.5
  3.  
  4. # Enter SECONDARY IP: 9.6.3.1
  5. # Enter another IP? Y/N: y
  6. # Enter SECONDARY IP: 8.9.6.6
  7. # Enter another IP? Y/N: n
  8. start to PING     <---------------------------------???????????????????????
  9.  
  10.  
but at the ping level
I receive this error msg:

Expand|Select|Wrap|Line Numbers
  1.  
  2.  File "E:/Carl Python/24 Octo 2007/test1.txt", line 81, in ping
  3.     pingaling =os.popen("ping %s" %(ipAdd),"r")
  4. NameError: global name 'ipAdd' is not defined   <------------???????????
  5.  
  6.  
Here is my code:

Expand|Select|Wrap|Line Numbers
  1.  
  2. import re
  3. import time 
  4. import thread 
  5. import os
  6. import sys
  7.  
  8. f=open('c:/tmp/primaryip.xls','w')
  9. f.close()
  10.  
  11. g=open('c:/tmp/workfile.txt','w')
  12. g.close()
  13.  
  14. h=open('c:/tmp/myprimarylogs.xls','w')
  15. h.close()
  16.  
  17. j=open('c:/tmp/secip.xls','w')
  18. j.close()
  19.  
  20. k = 1
  21. i = 1
  22. l = 1
  23.  
  24.  
  25. def validIP(ipAdd): 
  26.     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])$" 
  27.     re_ip = re.compile(ipRegex) 
  28.     return re_ip.match(ipAdd)
  29.  
  30. def validIP1(ipAdd1): 
  31.     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])$" 
  32.     re_ip = re.compile(ipRegex) 
  33.     return re_ip.match(ipAdd1)
  34.  
  35. print
  36. print time.asctime()
  37. print
  38. print   (' Ctrl+C to EXIT')
  39. print
  40.  
  41.  
  42. def ipAddress1(k):
  43.   ipAdd1 = raw_input("# Enter SECONDARY IP: ")
  44.   if validIP1(ipAdd1): #and k<3:
  45.         f=open('c:/tmp/secip.xls', 'a+')
  46.         f.write(ipAdd1+"\n")
  47.         f.close()
  48.         anotherip()
  49.   else: 
  50.         print "Wrong syntax"
  51.         ipAddress1(0)
  52.  
  53.  
  54. def ipAddress(i):
  55.  ipAdd = raw_input("# Enter Primary IP: ")
  56.  if i<2 and validIP(ipAdd) :
  57.         i=i+1
  58.         print i
  59.         f=open('c:/tmp/primaryip.xls', 'a+')
  60.         f.write(ipAdd+"\n")
  61.         f.close()
  62.         ipAddress1(0)
  63.  
  64.  else:
  65.         print "Wrong SYNTAXE"
  66.         ipAddress(0)
  67.  
  68.  
  69. def anotherip():
  70.     anotherip= raw_input("# Enter another IP? Y/N: " )
  71.     while anotherip.upper() == 'Y':  
  72.         ipAddress1(0)
  73.     if anotherip.upper() == 'N':
  74.         print ('start to PING')
  75.         ping(0)       #<---------------------------????????????????????????
  76.  
  77.     else:
  78.          print ('BYE!, Y/N not selected!')
  79.          sys.exit()
  80.  
  81.  
  82. def ping(l):
  83.          pingaling =os.popen("ping %s" %(ipAdd),"r")  #<------????????????
  84.          results = pingaling.read()
  85.          print results
  86.          for result in results:
  87.           for line in results:
  88.            g=open('c:/tmp/workfile.txt', 'a+')
  89.            g.write(line+"\n")
  90.            g.close()
  91.  
  92. ipAddress(0)
  93.  
  94.  
  95.  
Oct 24 '07 #7
bartonc
6,596 Expert 4TB
OK. Your IPs are in a file, right? SO:
Expand|Select|Wrap|Line Numbers
  1. def ping(l):
  2.     f=open('c:/tmp/secip.xls', 'a+')
  3.     ipList = ( line.strip() for line in f.readlines())
  4.     f.close()
  5.     for ipAdd in ipList:
  6.          pingaling =os.popen("ping %s" %(ipAdd),"r")  #<------????????????
  7.          results = pingaling.read()
  8.          print results
Oct 24 '07 #8
ilikepython
844 Expert 512MB
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.




Expand|Select|Wrap|Line Numbers
  1.  
  2. # Enter Primary IP: 2.3.6.5
  3.  
  4. # Enter SECONDARY IP: 9.6.3.1
  5. # Enter another IP? Y/N: y
  6. # Enter SECONDARY IP: 8.9.6.6
  7. # Enter another IP? Y/N: n
  8. start to PING     <---------------------------------???????????????????????
  9.  
  10.  
but at the ping level
I receive this error msg:

Expand|Select|Wrap|Line Numbers
  1.  
  2.  File "E:/Carl Python/24 Octo 2007/test1.txt", line 81, in ping
  3.     pingaling =os.popen("ping %s" %(ipAdd),"r")
  4. NameError: global name 'ipAdd' is not defined   <------------???????????
  5.  
  6.  
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:
Expand|Select|Wrap|Line Numbers
  1. ipAdd = raw_input("Enter primary IP: ")  # you would also validate this
  2. secondaryIPS = []
  3. while 1:
  4.     ipAdd2 = raw_input("Enter secondary IP: ") # again validate this
  5.     secondaryIPS.append(ipAdd2)
  6.     user_input = raw_input("Would you like to enter another IP address?: ")
  7.  
  8.     if user_input.lower() == 'n':
  9.         break
  10.  
  11.  
  12. print "Start ping"
  13. ping(ipAdd) # and pass anything you need in the ping() function.
  14.  
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?
Oct 24 '07 #9
bvdet
2,851 Expert Mod 2GB
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.




Expand|Select|Wrap|Line Numbers
  1.  
  2. # Enter Primary IP: 2.3.6.5
  3.  
  4. # Enter SECONDARY IP: 9.6.3.1
  5. # Enter another IP? Y/N: y
  6. # Enter SECONDARY IP: 8.9.6.6
  7. # Enter another IP? Y/N: n
  8. start to PING     <---------------------------------???????????????????????
  9.  
  10.  
but at the ping level
I receive this error msg:

Expand|Select|Wrap|Line Numbers
  1.  
  2.  File "E:/Carl Python/24 Octo 2007/test1.txt", line 81, in ping
  3.     pingaling =os.popen("ping %s" %(ipAdd),"r")
  4. NameError: global name 'ipAdd' is not defined   <------------???????????
  5.  
  6.  
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:
Expand|Select|Wrap|Line Numbers
  1. def ipAddress1(k):
  2.     while k<2:
  3.         global ipAdd1
  4.         ipAdd1 = raw_input("# Enter SECONDARY IP: ")
  5.         if k<1 and validIP1(ipAdd1):
  6.             .................
  7.  
Expand|Select|Wrap|Line Numbers
  1. def ipAddress(i):
  2.     global ipAdd
  3.     ipAdd = raw_input("# Enter Primary IP: ")
  4.     if i<2 and validIP(ipAdd) :
  5.          .....................
Oct 24 '07 #10
bartonc
6,596 Expert 4TB
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).
Oct 24 '07 #11
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:

Expand|Select|Wrap|Line Numbers
  1.  
  2. def ping(l):
  3.     f=open('c:/tmp/primaryip.xls', 'a+')
  4.     ipList = ( line.strip() for line in f.read()) ########################
  5.     f.close()
  6.     for ipAdd in ipList:
  7.          pingaling =os.popen("ping %s" %(ipAdd),"r")  
  8.          results = pingaling.read() ########################
  9.          print results
  10.          for result in results:
  11.           for line in results:
  12.            g=open('c:/tmp/workfile.txt', 'a+')
  13.            g.write(line+"\n")
  14.            g.close()
  15.     s=open('c:/tmp/secip.xls', 'a+')
  16.     ipList1 = ( line.strip() for line in s.read())########################
  17.     s.close()
  18.     for ipAdd1 in ipList1:
  19.          pingaling =os.popen("ping %s" %(ipAdd1),"r")  
  20.          results = pingaling.read()########################
  21.          print results
  22.          for result in results:
  23.           for line in results:
  24.             g=open('c:/tmp/workfile.txt', 'a+')
  25.             g.write(line+"\n")
  26.             g.close()
  27.     filter(0)
  28.  
Oct 24 '07 #12
bvdet
2,851 Expert Mod 2GB
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.
Expand|Select|Wrap|Line Numbers
  1. # imports
  2. def ping(*fnames):
  3.     g = open(fnames[0], 'w')
  4.     for fn in fnames[1:]:
  5.         f=open(fn, 'r')
  6.         ipList = [line.strip() for line in f.readlines()]
  7.         f.close()
  8.         resList = []
  9.         for ipAdd in ipList:
  10.             pingaling =os.popen("ping %s" %(ipAdd),"r")
  11.             resList.append(pingaling.read())
  12.         g.write('/n'.join(resList))
  13.     g.close()
  14.  
  15. def get_IPs(fnP, fnS):
  16.     # get a primary IP address and write it to file fnP
  17.     while True:
  18.         ipAddP = raw_input("# Enter Primary IP: ")
  19.         if validIP(ipAddP):
  20.             f = open(fnP, 'w')
  21.             f.write(ipAddP + "\n")
  22.             f.close()
  23.             break
  24.         else:
  25.             print "Invalid IP."
  26.  
  27.     ipList = []
  28.     # get a list if secondary IP addresses and write them to file fnS
  29.     while True:
  30.         while True:
  31.             ipAddS = raw_input("# Enter Secondary IP: ")
  32.             if validIP(ipAddS):
  33.                 ipList.append(ipAddS)
  34.                 break
  35.             else:
  36.                 print "Invalid IP"
  37.         s = raw_input("# Enter another IP? Y/N: " )
  38.         if s.upper() == "N":
  39.             f = open(fnS, 'w')
  40.             f.write('\n'.join(ipList))
  41.             f.close()
  42.             break
  43.  
  44. def read_data(fn):
  45.     f = open(fn)
  46.     for line in f:
  47.         if line.strip():
  48.             print line.strip()
  49.     f.close()
  50.  
  51. fnP = 'primaryip.txt'
  52. fnS = 'secip.txt'
  53. fnW = 'workfile.txt'
  54.  
  55. get_IPs(fnP, fnS)
  56. ping(fnW, fnP, fnS) 
  57. read_data(fnW)
Note that filter() is a built-in Python function.
Oct 25 '07 #13
bartonc
6,596 Expert 4TB
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.
Oct 25 '07 #14
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.xls


Expand|Select|Wrap|Line Numbers
  1.  
  2. def ping(*fnames):
  3.     g = open(fnames[0], 'w')
  4.     for fn in fnames[1:]:
  5.         f=open(fn, 'r')
  6.         ipList = [line.strip() for line in f.readlines()]
  7.         f.close()
  8.         resList = []
  9.         for ipAdd in ipList:
  10.             pingaling =os.popen("ping %s" %(ipAdd),"r")
  11.             resList.append(pingaling.read())
  12.         g.write('/n'.join(resList))
  13.     g.close()
  14.  
  15. def get_IPs(fnP, fnS):
  16.     # get a primary IP address and write it to file fnP
  17.     while True:
  18.         ipAddP = raw_input("# Enter Primary IP: ")
  19.         if validIP(ipAddP):
  20.             f = open(fnP, 'w')
  21.             f.write(ipAddP + "\n")
  22.             f.close()
  23.             break
  24.         else:
  25.             print "Invalid IP."
  26.  
  27.     ipList = []
  28.     # get a list if secondary IP addresses and write them to file fnS
  29.     while True:
  30.         while True:
  31.             ipAddS = raw_input("# Enter Secondary IP: ")
  32.             if validIP(ipAddS):
  33.                 ipList.append(ipAddS)
  34.                 break
  35.             else:
  36.                 print "Invalid IP"
  37.         s = raw_input("# Enter another IP? Y/N: " )
  38.         if s.upper() == "N":
  39.             f = open(fnS, 'w')
  40.             f.write('\n'.join(ipList))
  41.             f.close()
  42.             break
  43.  
  44. def read_data(fn):
  45.     f = open(fn)
  46.     for line in f:
  47.         if line.strip():
  48.             print line.strip()
  49.  
  50.  
  51.     f.close()
  52.  
  53. def fil():
  54.  for line in open("c:/tmp/workfile.txt"): 
  55.           s = 0
  56.           e = 0
  57.           loss_num = 0 # Initialize it
  58.           if line.startswith("Ping statistics for"):
  59.              ip=line.split()[-1][:-1]
  60.           if line.find("(")!=-1:
  61.              s=line.index("(")
  62.              e=line.index(")")
  63.              loss=line[s+1:e].replace("loss","")
  64.              print 'loss = ' + loss + ip
  65.              loss_num = loss.strip() # remove spaces if any
  66.              loss_num = loss_num.strip('%') # remove the % sign from loss       
  67.              print 'number = ' + loss_num
  68.           try:
  69.                 loss_num = float(loss_num) # change it into a number
  70.                 if loss_num >= 2 :
  71.                  output_line = loss + ',' + "'" + ip + "'" + "\n"
  72.                  s=open('myprimarylogs.xls', 'a+')
  73.                  s.write(line+"\n")
  74.                  s.close()
  75.                  ####################################### 
  76.           except:
  77.                  loss_num = ''
  78.                  mail()
  79.  
  80.  
  81. fnP = 'c:/tmp/primaryip.xls'
  82. fnS = 'c:/tmp/secip.xls'
  83. fnW = 'c:/tmp/workfile.txt'
  84.  
  85. get_IPs(fnP, fnS)
  86. ping(fnW, fnP, fnS) 
  87. read_data(fnW)
  88. fil()
  89.  
  90.  
  91.  
Oct 25 '07 #15
Hi Birtonc,

disregard...I did a stupid mystake,
was c:/tmp/myprimarylogs.xls not only myprimarylogs.xls : )
Oct 25 '07 #16
Hi Bartonc,

The script you provided give the ping to primary IP and than the Secondary,
but what about, if I want to Ping the primary but ping the Secondary ONLY if packet lost of the Primary if greater or equal.

The def fil() part that I put, Is filtering OK.

Brgds/Carl
Oct 25 '07 #17
bvdet
2,851 Expert Mod 2GB
Hi Bartonc,

The script you provided give the ping to primary IP and than the Secondary,
but what about, if I want to Ping the primary but ping the Secondary ONLY if packet lost of the Primary if greater or equal.

The def fil() part that I put, Is filtering OK.

Brgds/Carl
I modified your fil() function somewhat. I am using re to get the ip address and percentage loss. This will keep trying IPs until the list runs out or pinging is successful.
Expand|Select|Wrap|Line Numbers
  1. # imports, def validIP()
  2. def fil(data):
  3.     patt = re.compile(r'\((\d+)% loss\)')
  4.     patt1 = re.compile(r'(\d+.\d+.\d+.\d)')
  5.  
  6.     for line in data.split('\n'):
  7.  
  8.         if line.startswith("Ping statistics for"):
  9.             ip = patt1.search(line).group(1)
  10.  
  11.         if patt.search(line):
  12.             loss_num = int(patt.search(line).group(1))
  13.  
  14.             if loss_num >= 2 :
  15.                 s = open('myprimarylogs.txt', 'a+')
  16.                 s.write("%s '%s'\n" % (loss_num, ip))
  17.                 s.close()
  18.                 # if loss >= 2, return False - then secondary IPs are pinged
  19.                 print 'loss_num is >= 2 ', loss_num
  20.                 return False
  21.             else:
  22.                 print 'loss_num is < 2,', loss_num
  23.                 return True
  24.  
  25. def ping(*fnames):
  26.     g = open(fnames[0], 'w')
  27.     for fn in fnames[1:]:
  28.         f=open(fn, 'r')
  29.         ipList = [line.strip() for line in f.readlines()]
  30.         f.close()
  31.         resList = []
  32.         for ipAdd in ipList:
  33.             pingaling =os.popen("ping %s" %(ipAdd),"r")
  34.             data = pingaling.read()
  35.             resList.append(data)
  36.             # if loss > 2, ping secondary IPs
  37.             proceed = fil(data)
  38.             if proceed:
  39.                 break       
  40.         g.write('/n'.join(resList))
  41.         if proceed:
  42.             break
  43.     g.close()
  44.  
  45. def get_IPs(fnP, fnS):
  46.     while True:
  47.         ipAddP = raw_input("# Enter Primary IP: ")
  48.         if validIP(ipAddP):
  49.             f = open(fnP, 'w')
  50.             f.write(ipAddP.strip() + "\n")
  51.             f.close()
  52.             break
  53.         else:
  54.             print "Invalid IP."
  55.     ipList = []
  56.     while True:
  57.         while True:
  58.             ipAddS = raw_input("# Enter Secondary IP: ")
  59.             if validIP(ipAddS):
  60.                 ipList.append(ipAddS.strip())
  61.                 break
  62.             else:
  63.                 print "Invalid IP"
  64.         s = raw_input("# Enter another IP? Y/N: " )
  65.         if s.upper() == "N":
  66.             f = open(fnS, 'w')
  67.             f.write('\n'.join(ipList))
  68.             f.close()
  69.             break
  70.  
  71. fnP = 'primaryip.txt'
  72. fnS = 'secip.txt'
  73. fnW = 'workfile.txt'
  74.  
  75. get_IPs(fnP, fnS)
  76. ping(fnW, fnP, fnS)
Oct 25 '07 #18
Hi bvdet and Bartonc,

This work perfectly, you are real PROsss...
[EDIT: I've created a new thread for the additional question here]
It's here.
Oct 25 '07 #19

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Atul Kshirsagar | last post by:
Hello, I am using Python 2.3.2 with a C++ extention DLL in muti-threaded environment. 1. For each new thread I create a separate sub-interpreter. 2. Each thread executes multiple python...
7
by: ‘5ÛHH575-UAZWKVVP-7H2H48V3 | last post by:
(see end of message for example code) When an instance has a dynamically assigned instance method, deepcopy throws a TypeError with the message "TypeError: instancemethod expected at least 2...
5
by: Randall Parker | last post by:
Using Python 2.4.2 on Windows 2000 in SPE. Getting: TypeError: 'str' object is not callable on this line: TmpErrMsg1 = "State machine %s " (StateMachineName) In Winpdb 1.0.6 the...
1
by: Gary Wessle | last post by:
dear python users I am not sure why I am getting **************************************************************** Traceback (most recent call last): File "my.py", line 3, in ?...
10
by: Charles Russell | last post by:
Why does this work from the python prompt, but fail from a script? How does one make it work from a script? #! /usr/bin/python import glob # following line works from python prompt; why not in...
2
by: AWasilenko | last post by:
I'm trying to test a few different approaches to displaying pages via Cherrypy and I'm not having much luck. Here is my code so far: import sys, cherrypy, html class Root: @cherrypy.expose...
33
by: christophertidy | last post by:
Hi I am new to Python and have recieved this error message when trying to instantiate an object from a class from another file within the same directory and wondered what I have done wrong. I...
1
by: Traclo | last post by:
I am doing a computer science project and I have to take a string that contains numbers, double each number individually and then return the doubled integers as one large string. I tried this...
1
by: Charles Fox | last post by:
Hi gys -- I am looking at Numpy but getting this error when I try to get array sizes. I'm using Ubuntu Edgy with standard repositories and scipy. Any ideas? Am I doing something wrong or is it...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.