Guest User

Untitled

a guest
Nov 21st, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. # This script takes in an apache log file, parses the information and then posts it to a mysql database
  2. #
  3. # there was nothing in the instructions that specified that we aren't allowed to use libraries
  4. # so I chose to use the apache-log-parser library to make things easier on the parsing side,
  5. # and I also chose to use PeeWee as a simple ORM to update the database.
  6. # Harjot Kainth
  7. # 11.19.2017
  8. import apache_log_parser
  9. from peewee import *
  10.  
  11. db = MySQLDatabase(
  12. 'apache_logs',
  13. user='root',
  14. password='',
  15. host='localhost')
  16.  
  17.  
  18. class BaseModel(Model):
  19. class Meta:
  20. database = db
  21.  
  22.  
  23. class Log(BaseModel):
  24. remote_host = CharField()
  25. request_method = CharField()
  26. request_url = CharField()
  27. time_received = DateTimeField()
  28.  
  29.  
  30. # def create_tables():
  31. # db.connect()
  32. # db.create_table(Log)
  33. #
  34. # create_tables()
  35.  
  36. # path to file
  37. log_file_path = "access.log"
  38.  
  39. # open the file
  40. log_file = open(log_file_path, 'r')
  41.  
  42. # read in all lines
  43. logs = log_file.readlines()
  44.  
  45. # create log parser and specify format
  46. log_line_parser = apache_log_parser.make_parser("%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"")
  47.  
  48. # loop through each line in our logs
  49. for log in logs:
  50. # parse the line data
  51. log_line_data = log_line_parser(log)
  52.  
  53. # get required information for database from the line data and enter it into the database Model
  54. db.connect()
  55. log_data_object = Log(remote_host=log_line_data["remote_host"],
  56. request_method=log_line_data["request_method"],
  57. request_url=log_line_data["request_url"],
  58. time_received=log_line_data["time_received_datetimeobj"])
  59. # post information to database
  60. log_data_object.save()
  61. db.close()
Add Comment
Please, Sign In to add comment