Skip to content

Instantly share code, notes, and snippets.

@mijorus
Created December 16, 2023 10:59
Show Gist options
  • Save mijorus/2a506859ca8778f341b7bfd9d63cbfa6 to your computer and use it in GitHub Desktop.
Save mijorus/2a506859ca8778f341b7bfd9d63cbfa6 to your computer and use it in GitHub Desktop.
SambaConfig.py
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