Write regular expressions that will match IP addresses and usernames in a Microsoft IIS log file.
First, you will write a regular expression that matches IP addresses within the re.compile function call on line 36. Next, you will write a regular expression that matches usernames (in the format domain\username) on line 50. Finally, in steps 3 and 4 you will write a loop for each step that displays all the IP addresses (gathered into the list ipAddresses) and usernames (gathered in the list list users) to the console window.
# Import the regular expressions module
import re
# Function that takes a file and loads it into
# a Python list variable and returns that variable
def loadLogIntoList(filename):
with open(filename) as f:
lines = f.read().splitlines()
return lines
# Ask the user to input a file name
filename = input("Type in the filename for the log to analyze: ")
# Load each line of the file into a list of strings
lines = loadLogIntoList(filename)
# Create a placeholder variable (a list of strings) to
# hold the IP addresses and users we find in the log file
ipAddresses = []
users = []
# Loop through each line of the file
for line in lines:
#### Part 1: Create a new python regular expression object
#### by compiling an expression to look for an
#### IP address
ipRegEx = re.compile(r'REPLACE WITH A REGULAR EXPRESSION')
# Search the contents of each line for a match. If there is a
# match and that match doesn't already exist in the list, append
# it to the list
ipSearchResult = ipRegEx.search(line)
if ipSearchResult != None and ipSearchResult.group() not in ipAddresses:
ipAddresses.append(ipSearchResult.group())
#### Part 2: Create a new python regular expression object
#### by compiling an expression to look for a user
#### account(as a DOMAIN\username combination)
userRegEx = re.compile(r'REPLACE WITH A REGULAR EXPRESSION')
# Search the contents of each line for a match. If there is a
# match and that match doesn't already exist in the list, append
# it to the list
userSearchResult = userRegEx.search(line)
if userSearchResult != None and userSearchResult.group() not in users:
users.append(userSearchResult.group())
#### Part 3: Loop through each IP address and display
#### each IP address found to the user
# WRITE CODE HERE
#### Part 4: Loop through each username (shown as a
#### DOMAIN\username combination) to the user
# WRITE CODE HERE
def isPhoneNumber(text):
❶ if len(text) != 12:
return False
for i in range(0, 3):
❷ if not text[i].isdecimal():
return False
❸ if text[3] != '-':
return False
for i in range(4, 7):
❹ if not text[i].isdecimal():
return False
❺ if text[7] != '-':
return False
for i in range(8, 12):
❻ if not text[i].isdecimal():
return False
❼ return True
print('415-555-4242 is a phone number:')
print(isPhoneNumber('415-555-4242'))
print('Moshi moshi is a phone number:')
print(isPhoneNumber('Moshi moshi'))
Get Answers For Free
Most questions answered within 1 hours.