checklogfile.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import time, sys, getopt, os, random
  4. ip = ""
  5. login = "admin"
  6. password = "12345"
  7. def usage():
  8. print "Usage:\r\n\
  9. checklogfile.py <filename> - to check local log file\r\n\
  10. checklogfile.py -d <ip-address> - to download and check log file"
  11. def parse(path):
  12. f = open(path)
  13. lines = [line.rstrip('\n') for line in f]
  14. #Remove UTF8 BOM
  15. lines[0] = lines[0].replace('\xEF\xBB\xBF','')
  16. #Remove empty lines
  17. for i in range(len(lines)-1, len(lines)-10, -1):
  18. #print "str -", i, lines[-i]
  19. if lines[i] == " "*118+"\x0D":
  20. del lines[i]
  21. print "len: ", len(lines)
  22. return lines
  23. def do_login():
  24. os.system("curl -s -b /tmp/cookies.txt -c /tmp/cookies.txt -d \"login=%s&password=%s\" http://%s/login.cgi > /dev/null" % (login, password, ip))
  25. def log_download(path):
  26. print "Downloading log file..."
  27. if 0 == os.system("curl -b /tmp/cookies.txt -c /tmp/cookies.txt \"http://%s/history.cgi?page=all&_=%s\" --output %s --progress" % (ip, random.randint(0, 0xFFFF), path)):
  28. return True
  29. else:
  30. return False
  31. def check(path):
  32. lines = parse(path)
  33. lastptr = 0
  34. for i in range(len(lines)):
  35. #i = lines.index(s)
  36. s = lines[i]
  37. print "\rProcessing: %d%%" %( (i+1)*100/len(lines)),
  38. #Check if string in valid format
  39. if len(s) > 119 or s[0] != '"' or s.count('"') != 2 or s.count('\x00') != 0:
  40. print "\nError. Log file is corrupted:"
  41. print "Wrong string (at index %d) : %s" %(i+1, s)
  42. return False
  43. strdate = s.replace('"','').split(";")[3].rstrip()
  44. #print strdate
  45. newdate = time.strptime(strdate, "%d.%m.%y %H:%M:%S")
  46. if i != 0:
  47. if newdate < lastdate:
  48. if lastptr == 0:
  49. lastptr = i+1
  50. else:
  51. print "\nError. Wrong message order!"
  52. print "Look at index:", i+1
  53. lastdate = newdate
  54. print "\nLast message index:", lastptr
  55. print "Log file is OK"
  56. return True
  57. def main():
  58. global ip
  59. try:
  60. opts, args = getopt.getopt(sys.argv[1:], "hd:", \
  61. ["help", "download="])
  62. except getopt.GetoptError:
  63. usage()
  64. sys.exit(2)
  65. for opt, arg in opts:
  66. if opt in ("-h", "--help"):
  67. usage()
  68. sys.exit()
  69. if opt in ("-d", "--download"):
  70. ip = arg
  71. if ip == "" and len(sys.argv) < 2:
  72. usage()
  73. sys.exit(2)
  74. if ip == "":
  75. path = sys.argv[-1]
  76. else:
  77. path = "/tmp/checklog.csv"
  78. do_login()
  79. if not log_download(path):
  80. print "Download error"
  81. sys.exit(2)
  82. check(path)
  83. if __name__ == "__main__":
  84. main()