Python 使用 configparser 模块解析类似 windows 系统中 .ini 类型的配置文件。Samba 的配置文件正是采用这种格式,因此解析起来非常简单。

解析并打印配置信息

第一步 创建名为 parser-smb.py 文件

// 导入模块
import configparser

// 创建解析器对象并禁用 interpolation 功能
config = configparser.ConfigParser(interpolation=None)

// 读取 samba 配置文件
config.read('./smb.conf')

// 循环打印配置信息,主循环打印 section 名称,子循环打印当前 section 下的键和值。
for section in config.sections():
    print('[' + section + ']')
    for k,v in config.items(section):
        print(k + ' = ' + v)
    print('')

提示:interpolationConfigParser 对象提供的变量功能,它会与 samba 配置文件中的定义 % 变量发生冲突,因此在实例化对象的时候要将其禁用。

第二步 运行程序

$ python3 parser-smb.py

[global]
workgroup = WORKGROUP
dns proxy = no
log file = /var/log/samba/log.%m
max log size = 1000
syslog = 0
panic action = /usr/share/samba/panic-action %d
server role = standalone server
passdb backend = tdbsam
obey pam restrictions = yes
unix password sync = yes
passwd program = /usr/bin/passwd %u
passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .
pam password change = yes
map to guest = bad user
usershare allow guests = yes

[homes]
comment = Home Directories
browseable = no
read only = yes
create mask = 0700
directory mask = 0700
valid users = %S

[printers]
comment = All Printers
browseable = no
path = /var/spool/samba
printable = yes
guest ok = no
read only = yes
create mask = 0700

[print$]
comment = Printer Drivers
path = /var/lib/samba/printers
browseable = yes
read only = yes
guest ok = no