0

Samba 構成を読み取り、さまざまな「セクション」をループして、変数が設定されている場合に動作する bash スクリプトを作成しようとしています

構成例を次に示します。

[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}行の先頭に一致し、行の終わりまで0文字以上^が続き、一致する場合は印刷されません[.*$!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 に答える