0

我正在尝试创建一个 bash 脚本,该脚本将读取 samba 配置,遍历不同的“部分”并在设置变量时采取行动

这是一个示例配置:

[global]
    workgroup = METRAN
    encrypt passwords = yes
    wins support = yes
    log level = 1 
    max log size = 1000
    read only = no
[homes] 
    browsable = no
    map archive = yes
[printers] 
    path = /var/tmp
    printable = yes
    min print space = 2000
[music]
    browsable = yes
    read only = yes
    path = /usr/local/samba/tmp
[pictures]
    browsable = yes
    read only = yes
    path = /usr/local/samba/tmp
    force user = www-data

这是我想做的事情(我知道这种语法是一种真正的语言,但它应该给你一个想法:

#!/bin/sh
#
CONFIG='/etc/samba/smb.conf'
sections = magicto $CONFIG    #array of sections
foreach $sections as $sectionname       #loop through the sections
  if $sectionname != ("homes" or "global" or "printers")
    if $force_user is-set
       do something with $sectionname and with $force_user
    endif
    else
       do something with $sectionname
    endelse
  endif
endforeach
4

3 回答 3

1

这将读取每个部分并获取键值对。

#!/bin/bash
CONFIG='/etc/samba/smb.conf'
for i in homes music; do
    echo "$i"
    sed -n '/\['$i'\]/,/\[/{/^\[.*$/!p}' $CONFIG | while read -r line; do
        printf "%-15s : %s\n" "${line%?=*}" "${line#*=?}"
    done
done

输出

homes
browsable  : no
map archive : yes
music
browsable  : yes
read only  : yes
path       : /usr/local/samba/tmp

解释

  • sed -n '/\['$i'\]/,/\[/{/^\[.*$/!p}'

    1)/\['$i'\]/,/\[/匹配[]直到下一个之间的部分名称[

    2){/^\[.*$/!p}匹配行首,^后跟[零个或多个字符.*,直到行尾$,如果匹配不打印!p

  • ${line%?=*}从末尾(右)修剪字符串,直到第一个=和任何字符?

  • ${line#*=?}从开始(左)到第一个=和任何字符修剪字符串?
于 2012-12-07T05:09:42.900 回答
0

使用 Perl:

use strict;
use warnings;

sub read_conf {
  my $conf_filename = shift;
  my $section;
  my %config;
  open my $cfile, "<", $conf_filename or die ("open '$conf_filename': $!");
  while (<$cfile>) {
    chomp;
    if (/^\[([^]]+)]/) {
      $section = $1; 
    } else {
      my ($k, $v) = split (/\s*=\s*/);
      $k =~ s/^\s*//;
      $config{$section}{$k} = $v; 
    }   
  }
  close $cfile;
  return \%config;
}

sub main {
  my $conf_filename = '/etc/samba/smb.conf';
  my $conf = read_conf($conf_filename);
  foreach my $section (grep { !/homes/ and !/global/ and !/printers/} keys %$conf) {
    print "do something with: $section\n";
    foreach my $key (keys %{$conf->{$section}}) {
      my $val = $conf->{$section}{$key};
      print "$key is $val in $section\n";
    }   
  }
}

main;
于 2012-12-07T00:21:45.460 回答
0

如果你熟悉 Perl,你可以看看 Config::Std

http://metacpan.org/pod/Config::Std

对这个问题的赞美:如何在 Perl 中找到与正则表达式的所有匹配项?

于 2012-12-07T00:29:15.957 回答