Created
December 16, 2023 10:59
-
-
Save mijorus/2a506859ca8778f341b7bfd9d63cbfa6 to your computer and use it in GitHub Desktop.
SambaConfig.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
from pprint import pprint | |
class SambaConfig(): | |
def __init__(self) -> None: | |
self.data = {} | |
self.original_raw_data = {} | |
def get_seciton(self, section: str) -> dict: | |
return self.data.get(f'[{section}]', None) | |
def create_section(self, section: str): | |
self.data[f'[{section}]'] = {} | |
def parse(self, file_path='/etc/samba/smb.conf'): | |
"""Parse a smb file""" | |
content = '' | |
with open(file_path, 'r') as f: | |
content = f.read() | |
lines = content.split('\n') | |
section_re = re.compile(r'\[(.*)\]') | |
self.data = {} | |
curr_section = None | |
for line in lines: | |
line = line.strip() | |
if not line or line.startswith(';') or line.startswith('#'): | |
continue | |
if section_re.match(line): | |
self.data[line] = {} | |
self.original_raw_data[line] = {} | |
curr_section = line | |
else: | |
key, value = line.split('=', 1) | |
key = key.strip().replace(' ', '_') | |
value = value.strip() | |
parsed_value = value | |
if value in ['yes', 'no', '1', '0', 'true', 'false']: | |
parsed_value = value in ['yes', '1', 'true'] | |
self.data[curr_section][key] = parsed_value | |
self.original_raw_data[curr_section][key] = value | |
samba_conf = SambaConfig() | |
samba_conf.parse('smb.conf') | |
pprint(samba_conf.data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment