Python Forum

Full Version: Remove part of the code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
The following code checks both the username and the MAC address:
#!/usr/bin/python3

import re
import sys


db_file = '/etc/openvpn/db.txt'
log_file = '/var/log/openvpn/openvpn.log'
regex_mac = 'IV_HWADDR=(.*)'
regex_username = 'depth=0, CN=(.*)'
login = False

logs_username_mac_list = []


with open(log_file, 'r') as log:
    lines = log.readlines()
    # read only latest 100 lines
    last_50_lines = lines[-50:]
    # iterate latest 50 lines
    for line in last_50_lines:


        match_mac = re.search(regex_mac, line)
        if match_mac:
            log_mac = match_mac.group(1)
            print(log_mac)
            # on match, add it to list
            logs_username_mac_list.append(log_mac)

        match_username = re.search(regex_username, line)
        if match_username:
            log_username = match_username.group(1)
            print(log_username)
            logs_username_mac_list.append(log_username)

# fetch username and mac address from database
with open(db_file, 'r') as db:
    for line in db.readlines():
       
        splitter = line.split('-', 1)
        # 0 index is username, removing newline
        db_username = (splitter[0]).rstrip("\n")
        print(db_username)
        # 1 index is mac, removing newline
        db_mac = (splitter[1]).rstrip("\n")
        print(db_mac)
        if db_username in logs_username_mac_list:
            user_index = logs_username_mac_list.index(db_username) - 1
            print(user_index)
            mac_index = logs_username_mac_list[user_index]
            print(user_index)
            # if log mac matches db_mac
            if mac_index == db_mac:
                print("true")
                login = True
                print(login)

if login:
    sys.exit(0)
else:
    sys.exit(1)
I just want the MAC address to be checked. I changed the code as follows:
#!/usr/bin/python3

import re
import sys


db_file = '/etc/openvpn/db.txt'
log_file = '/var/log/openvpn/openvpn.log'
regex_mac = 'IV_HWADDR=(.*)'
login = False

logs_mac_list = []


with open(log_file, 'r') as log:
    lines = log.readlines()
    # read only latest 100 lines
    last_50_lines = lines[-50:]
    # iterate latest 50 lines
    for line in last_50_lines:


        match_mac = re.search(regex_mac, line)
        if match_mac:
            log_mac = match_mac.group(1)
            print(log_mac)
            # on match, add it to list
            logs_mac_list.append(log_mac)

# fetch username and mac address from database
with open(db_file, 'r') as db:
    for line in db.readlines():
       
        splitter = line.split('-', 1)
        # 1 index is mac, removing newline
        db_mac = (splitter[1]).rstrip("\n")
        print(db_mac)
        mac_index = logs_mac_list[user_index]
        print(user_index)
        # if log mac matches db_mac
        if mac_index == db_mac:
            print("true")
            login = True
            print(login)

if login:
    sys.exit(0)
else:
    sys.exit(1)
Is it OK?

Thank you.
No. user_index is undefined on line 38. Since the old logic verifies the user's mac address, it cannot be used if you want to ignore the user. What are you trying to verify?

The code below compares mac addresses in the last 50 lines against the database and reports the number of mismatches.
#!/usr/bin/python3
import re
import sys
 

# Make set of all valid mac addresses from db file.
with open('/etc/openvpn/db.txt', 'r') as file:
    mac_db = {line.split('-', 1)[1].rstrip() for line in file}

# Verify login attempts against the mac address set.
regex_mac = re.compile('IV_HWADDR=(.*)')
invalid_count = 0
with open('/var/log/openvpn/openvpn.log', 'r') as file:
    for line in file.readlines()[-50:]:  # Only looking at last 50 lines
        if (match := re.search(regex_mac, line)):
            if match.group(1) not in mac_db:
                print("Invalid mac:", line)
                invalid_count += 1
sys.exit(invalid_count)
(Jan-06-2024, 10:23 PM)deanhystad Wrote: [ -> ]for line in file.readlines()[-50:]:  # Only looking at last 50 lines
If you don't want to store all the lines of the file at once, you can write
from collections import deque
...
for line in deque(file, maxlen=50): # only looking at last 50 lines
    ...
(Jan-06-2024, 10:23 PM)deanhystad Wrote: [ -> ]No. user_index is undefined on line 38. Since the old logic verifies the user's mac address, it cannot be used if you want to ignore the user. What are you trying to verify?

The code below compares mac addresses in the last 50 lines against the database and reports the number of mismatches.
#!/usr/bin/python3
import re
import sys
 

# Make set of all valid mac addresses from db file.
with open('/etc/openvpn/db.txt', 'r') as file:
    mac_db = {line.split('-', 1)[1].rstrip() for line in file}

# Verify login attempts against the mac address set.
regex_mac = re.compile('IV_HWADDR=(.*)')
invalid_count = 0
with open('/var/log/openvpn/openvpn.log', 'r') as file:
    for line in file.readlines()[-50:]:  # Only looking at last 50 lines
        if (match := re.search(regex_mac, line)):
            if match.group(1) not in mac_db:
                print("Invalid mac:", line)
                invalid_count += 1
sys.exit(invalid_count)

Hello,
Thank you so much for your reply.
I don't like to report the number of mismatches. As you can see in the original code, if the MAC address is not in the file /etc/openvpn/db.txt, then login is not allowed, otherwise login is allowed.
No idea what you mean by "not allowed" since you are looking in a log file at logins that have already happened.
(Jan-08-2024, 05:57 AM)deanhystad Wrote: [ -> ]No idea what you mean by "not allowed" since you are looking in a log file at logins that have already happened.

Hello,
Thank you so much for your reply.
Please take a look at https://medium.com/@jagdish.bairagi/how-...aad49e412e. I think you understand what I mean. I just want the MAC address to be checked.