Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi All

I have wrote the script below to edit the postfix virtual file that contains the e-mail address to username mappings, and add new users. I need to modify it so that it can add more than one domain.
my $username = "bob"; my $datafile = '/etc/postfix/virtual' ; my $req_addr = "$username\@test1.com" ; #Edit Postfix Virtual File my ( $name, $domain ) = $req_addr =~ /^([\w.-]+)(@[\w.-]+)$/ ; open FH, $datafile or die "Couldn't read $datafile: $!" ; my @virtual = <FH> ; close FH ; open FH, ">$datafile" or die "Couldn't write $datafile: $!" ; my $wrote_it = 0 ; for ( @virtual ) { print FH $_ ; if ( $_ =~ /test1.com/ && !$wrote_it ) { print FH "$req_addr\t$username\n" ; $wrote_it++ ; } } close FH ;
It is currently adding data to the virtual file for the domain test1.com, but i want to be able to search and add data for another domain e.g test2.com. Ideas?

Replies are listed 'Best First'.
Re: Postfix Virtual Edit Script
by edoc (Chaplain) on May 03, 2003 at 14:41 UTC

    not entirely sure this does all that you're after, but it should give you a few ideas..

    I haven't actually ever written anything that takes commandline options before, so thought I'd have a crack!

    I'm assuming here that your file simply contains:
    @dom1.com fred
    @dom2.com sarah
    @dom3.com tony
    etc..

    usage: pfvedit -u bob -a @test2.com

    #!/usr/bin/perl -w use strict; # single-character switches processing with switch clustering use Getopt::Std; # declare globals our ($opt_u,$opt_a); # the actual postfix file #my $datafile = '/etc/postfix/virtual' ; my $datafile = "evpostdata.txt"; # a temp file we'll use for writing #my $tempfile = '/tmp/pfvirtual'; my $tempfile = "evposttemp.txt"; # get the supplied args (go into $opt_u,$opt_a) getopt('ua'); # make sure args are present usage() unless($opt_u && $opt_a); # make sure args are ok usage() unless $opt_u =~ /^\w+$/; usage() unless $opt_a =~ /^\@[\w\.\-]{3,}$/; # read the existing postfix file open FH, $datafile or die "Couldn't read $datafile: $!" ; my @virtual = <FH>; close FH ; # add our new line push(@virtual,"$opt_a\t$opt_u"); # slice n dice into an array of arrays for sorting foreach(@virtual){ chomp $_; my ($addr,$user) = split(/\t/,$_); $_ = [ $addr, $user ]; } # sort by usernames @virtual = sort { $a->[1] cmp $b->[1] } @virtual; # sort by domains @virtual = sort { $a->[0] cmp $b->[0] } @virtual; # write data to temp file open FH, ">$tempfile" or die "Couldn't write $datafile: $!" ; foreach(@virtual){ print FH "$_->[0]\t$_->[1]\n"; } close FH; # move new file to real location rename($tempfile,$datafile); print "Added user '$opt_u' with address '$opt_a'.\n"; exit; sub usage{ print "usage: evpostfix -u USER -a \@domain.com\n"; exit; }